如何用 C 中给定整数的数字填充数组?

How do I populate an array with the digits of a given integer in C?

假设您在代码中声明了一个整数

int my_num = 967892; 

你有一个数组

int a[6]; 

如何将该整数放入数组中,使其看起来像这样?

{ 9, 6, 7, 8, 9, 2 }

大概是这样的:

const unsigned char digits[] = { 9, 6, 7, 8, 9, 2 };

但是你的问题当然有很多不清楚的地方。

如果您想在运行时执行此操作,正如您现在的评论让我相信的那样,您当然需要更多代码。此外,使数组 "fit" 准确地成为数字将很棘手,因为这需要运行时调整数组的大小。

核心操作是 % 10,当应用于数字时会产生最右边的数字("ones" 数字)。

如果动态完成:

  1. 确定位数为N.
  2. 分配一个足够大的数组 (>=N) 来保存数字。
  3. 循环 N 次截断数字并将它们存储在 2 下分配的数组中。

我假设您想实现这样的目标:

int arr[SOME_SIZE];
int len = int_to_array(arr,421);
assert(len == 3);
assert(arr[0] == 4);
assert(arr[1] == 2);
assert(arr[1] == 1);

因为这可能是一道作业题,我不会给出完整的答案,但你会想要一个循环,你会想要一种从 int 和 int 中获取最后一位小数的方法删除最后一位数字。

所以这里有一个提示:

421 / 10 == 42
421 % 10 == 1

如果你想创建一个长度合适的数组,有多种方法:

  • 你可以循环两次;一次计算数字(然后创建数组);再次填充
  • 您可以填充一个比您需要的更大的数组,然后创建一个新数组并根据需要复制尽可能多的成员
  • 您可以填充一个比您需要的更大的数组,然后使用 realloc() 或类似的(我们以前没有的奢侈品!)

最低位是 num % 10

下一位可以通过num/=10找到;

这适用于正数,但实现定义为负数

您可以通过获取每个数字并将其放入数组中来完成此操作。感谢@unwind 考虑使用 unsigned int 因为数字没有符号。没想到

DISClAIMER:此代码未经测试,但从理论上讲,如果我没有犯任何社区会发现的错误,就可以完成您的任务。

注意:当theNum为负数时,该程序是实现定义的。有关这意味着什么的更多信息,请参阅 this SO 问题。此外,在这个 post 是重复的问题中,接受的答案比这个更短,但使用 log10 ,这(根据评论者)可能不准确。

//given theNum as the number
int tmp = theNum;
int magnitude = 0;
//if you keep dividing by 10, you will eventually reach 0 (integer division)
//and that will be the magnitude of the number + 1 (x * 10^n-1)
for (; tmp > 0; magnitude++){ //you could use a while loop but this is more compact
    tmp /= 10;
}
//the number of digits is equal to the magnitude + 1 and they have no sign
unsigned int digits[magnitude];
//go backwards from the magnitude to 0 taking digits as you go
for (int i = magnitude - 1; i > 0; i--){
    //get the last digit (because modular arithmetic gives the remainder)
    int digit = theNum % 10;
    digits[i] = digit; //record digit
    theNum /= 10; //remove last digit
}