【发布时间】:2019-03-21 09:31:27
【问题描述】:
我必须为学校计算数字总和的代码。由于它必须处理大数字(80 000 位以上),我必须首先将其视为一个数组,因为即使在 long long int 中也无法放入这个大数字。我的问题是为什么这段代码不起作用? (适用于较小的数字,例如:10^100)但是当我尝试非常大的数字(10^10000)时,它不能正常工作。任何人都可以通过说如何或帮助我解决这个问题来帮助我吗?谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char pole [100000];
int c = 0;
int sum = 0;
int x = 0;
int t;
printf("Nacitaj cislo!\n");
scanf("%s", pole);
printf("Zadal si: %s\n", pole);
while (pole[c] != '\0') {
t = pole[c] - '0';
sum = sum + t;
c++;
}
while(1){
while(sum != 0){
x = x + sum % 10;
sum = sum/10;
}
if(x > 10){
sum = x;
}
else{
break;
}
}
printf("%d\n", x);
return 0;
}
【问题讨论】:
-
请定义它不能正常工作?您是否在示例中得到负值?
-
究竟是什么不起作用?最引人注目的是
char pole [100000];,如果你先使用char *pole = malloc(100000);,然后在最后使用free(pole);,它会起作用吗? -
+1 给 Blaze。也可能值得看看stackoverflow.com/questions/3144135/…
-
@RóbertPorubän 你得到了负值,因为在某些时候,你溢出了 int 的最大大小。尝试将值存储在 char 数组而不是数字中
-
在最后一个循环中,你最终计算了数字根,你不应该为每一步重置
x吗?