如何将整数值转换为整数数组格式?
例如:
int answer = 140;
我希望得到的期望值是:
int arr_answer[] = { 1, 4, 0};
如何将整数值转换为整数数组格式?
例如:
int answer = 140;
int arr_answer[] = { 1, 4, 0};
如果您事先知道位数(在此例中为 3),可以按照以下方式进行:
#include <stdio.h>
int main()
{
const int numDigits = 3;
int answer = 140;
int digits[numDigits];
int i = numDigits - 1;
while (answer > 0)
{
int digit = answer % 10;
answer /= 10;
digits[i] = digit;
printf("digits[%d] = %d\n", i, digits[i]);
i--;
}
return 0;
}
输出:
digits[2] = 0
digits[1] = 4
digits[0] = 1
0 4 1
is wrong. Fix your code. It should be 1 4 0
- Michi一种选择是计算数字并使用可变长度数组1:
#include <stdio.h>
int main(void){
int ans = 140;
int x = ans;
size_t i, size = 0;
while ( x ) {
x=x/10;
size++;
}
int arr_answer[size];
for ( i = size - 1, x = ans ; x ; x = x/10, i-- ) {
arr_answer[i] = x % 10;
}
for ( i=0 ; i < size ; i++ ) {
printf("%d ", arr_answer[i]);
}
}
size
,因此避免了第一次循环。但这可能是唯一创建确切大小数组的方式。或者,如果数字的数量可能非常庞大(并且您需要以不同的方式存储它们-一个int
只能容纳有限范围的值),您也可以使用malloc()
(如果您不需要使用数组)来分配内存块。
1 自C99以来可用的VLA是C11中的可选功能。
我不是C程序员,所以无法提供具体的代码,但我建议尝试以下两种方法:1)将整数转换为字符串(谷歌建议使用sprintf()函数),2)运行一个for循环,遍历整数/字符串的长度并将其赋值给一个数组。我最终会做出类似于以下的代码:
integer_String = convertToString(integer)
for (integer_String.length()) {assign to array}
最好将其封装在一个返回数组的函数中。
编辑:无视我之前的回答,哈哈,其他答案更好。
answer
中有多少位数字吗? - bejadoint arr_answer[] = { 1, 4, 0};
的源代码吗?请具体说明。 - Weather Vane