C语言 如何将整数放入数字数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18691677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:23:34  来源:igfitidea点击:

How to put an integer to an array of digits

c

提问by Destructor

I want to put a number like 123456 in to a array of digits. Could you please give me a hint to the process? Can i define an array with unknown number of elements?

我想将 123456 之类的数字放入数字数组中。你能给我一个过程的提示吗?我可以定义一个元素数量未知的数组吗?

回答by Umang Mehta

First calculate no of digits

首先计算位数

int count = 0;
int n = number;

while (n != 0)
{
    n /= 10;
    cout++;
}

Now intialize the array and assign the size:

现在初始化数组并分配大小:

if(count!=0){
   int numberArray[count];

   count = 0;    
   n = number;

   while (n != 0){
       numberArray[count] = n % 10;
       n /= 10;
       count++;
   }
}

回答by jxh

If you don't mind using charas the array element type, you can use snprintf():

如果您不介意char用作数组元素类型,则可以使用snprintf()

char digits[32];
snprintf(digits, sizeof(digits), "%d", number);

Each digit will be represented as the character values '0'though '9'. To get the integer value, subtract the character value by '0'.

'0'尽管每个数字都将表示为字符值'9'。要获得整数值,请将字符值减去'0'

int digit_value = digits[x] - '0';

回答by Nanhe Kumar

int x[6];
int n=123456;
int i=0;
while(n>0){
   x[i]=n%10;
   n=n/10;
   i++;
}

回答by P0W

"Can i define an array with unknown number of elements ?"

“我可以定义一个元素数量未知的数组吗?”

If the number is too large you can input it as string and then accordingly extract digits from it

如果数字太大,您可以将其输入为字符串,然后相应地从中提取数字

Something like following :

类似于以下内容:

char buf[128];
int *array;
//fscanf(stdin,"%s",buf);

array = malloc(strlen(buf) * sizeof(int)); //Allocate Memory
int i=0;
do{
 array[i] = buf[i]-'0'; //get the number from ASCII subtract 48
 }while(buf[++i]); // Loop till last but one 

回答by Manoj Pandey

Here are teh steps. First, get the size needed to store all the digits in the number -- do a malloc of an array. Next, take the mod of the number and then divide the number by 10. Keep doing this till you exhaust all digits in the number.

这是步骤。首先,获取存储数字中所有数字所需的大小——对数组进行 m​​alloc。接下来,取数字的模数,然后将数字除以 10。继续这样做,直到用完数字中的所有数字。