c - 在C中手动将4位int(十进制)提取到字符串中

标签 c arrays string char int

我正在为我的一门类(class)的编程作业而苦苦挣扎。我是一名电气工程专业的学生,​​所以我的编程一点也不令人惊奇。我被告知编写一个 C 程序,该程序接受一个 12 位数字并将该 12 位数字的每个数字提取到一个 char 数组中。我快速算了一下,发现我们能获得的最大数字是 0xFFF 或十进制的 4095。我发现了一种我认为可以很好地工作的算法,但由于某种原因,我的代码没有按照我的想法进行。我正在继续尝试解决这个问题,但由于我运行它的唯一方法是在 Linux 终端窗口中,所以我没有一个很好的调试实用程序来单步调试程序。任何帮助将不胜感激。也请随意提出一些问题,我会尽力解答。我不是一个流利的程序员,所以请记住这一点。另外,如果有人可以向我解释整数除法,那将会很有帮助。我假设像 8/10 这样的东西会返回 0 结果,但我不知道当我运行程序时它是这样工作的。谢谢。

我无法使用函数来执行此操作,必须手动执行。

这是我迄今为止所拥有的。

尝试@解决方案:

//12 bit value into string of decimal chars
//EX: 129 -> a '1' a '2' and a '9'

void main (void) {

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stddef.h>
//Initialize an array with 5 spaces, each space
//holds one character (accounts for largest number 4095)
char OUT[5];
uint8_t length = sizeof(char);

//Isolating each int value happens here
//initialize i to act as a counter to loop through array
uint8_t i=2;
//Initialize an input value to test the code;
uint16_t IN=549;

while (IN/10 > 0)
 {
OUT[length-(i+1)] = '0' + (IN%10);
 IN=IN/10;
 if (IN <= 10)
      {
      if (IN = 10) 
           {
           OUT[length-(i+1)] ='1';
           //fixes infinite loop issue               
           IN=0;
           }
      else
           {
           OUT[length-(i+1)] ='0' + IN;
           //fixes infinite loop issue               
           IN=0;
           }

      }
 //Increment Counter to keep track of char array    
 i++;
 }
//add the new line at the end of the array of chars
OUT[length-1]='\n';
printf("String is -> %s", OUT);

}

一些注意事项: 使用 IN%10 是隔离十进制最右边数字的算法的一部分。我必须在计数器中添加一些“模糊因素”,以使数组正确排列并考虑到字符数组末尾的\n 。我在 while 循环中放入的条件语句是为了捕获一些边缘情况(主要是当 IN 变为 10 或更少时)。

最佳答案

看起来您正在竭尽全力来处理必须首先打印最左边的字符这一事实。如果先生成最右边的字符,然后反转它,逻辑就简单得多。

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stddef.h>
#include <string.h>

//12 bit value into string of decimal chars
//EX: 129 -> a '1' a '2' and a '9'
void main (void) {

    char OUT[5];
    memset(OUT, 0, 5);

    int i=0;
    int j;
    uint16_t IN=549;

    // Generate the string in reverse order.
    while (IN != 0)
    {
        OUT[i++] = '0' + (IN%10);
        IN/=10;
    }

    // Reverse the string
    for (j = 0; j < i/2; j++) {
        char temp = OUT[j];
        OUT[j] = OUT[i-1-j];
        OUT[i-1-j] = temp;
    }

    printf("String is -> %s\n", OUT);

}

关于c - 在C中手动将4位int(十进制)提取到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26318361/

相关文章:

c - 错误 : cannot convert 'char**' to 'char*' in initialization for strings

c - 为什么我无法打开另一个文件?

java android 新字符串

c - C中链表的标准实现

c - 为什么 offsetof 返回 size_t 而不是 uintptr_t?

arrays - Julia:数组赋值行为

javascript - 如何从 JavaScript 中的对象内部解构数组?

c++ - 试图让 array.length 在 for 循环中工作

java - 在 Java 中转换 'ArrayList<String> to ' String[]'

java - 有没有更有效的方法来计算每个连续字母在字符串中出现的次数? (java)