我新学习C语言,尝试编写一个计算2^n的所有数字和的程序,其中n<10^8。
例如,对于2^10,我们会有1+0+2+4,这是7。
以下是我编写的代码:
问题在于:当数字小于30时,程序正常工作。一旦我将n设置为大于30的数字,结果始终是-47。
我真的不理解这个错误及其原因。
以下是我编写的代码:
#include <stdio.h>
#include <math.h>
int main()
{
int n, t, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d", &n);
t = pow(2, n);
while (t != 0)
{
remainder = t % 10;
sum = sum + remainder;
t = t / 10;
}
printf("Sum of digits of 2 to the power of %d = %d\n", n, sum);
return 0;
}
问题在于:当数字小于30时,程序正常工作。一旦我将n设置为大于30的数字,结果始终是-47。
我真的不理解这个错误及其原因。
n
是多少? - Ry-int
类型,同时允许任何n
的值吗?所以最大可以到INT_MAX
,这可能是32,767或2,147,483,647? - Ry-