我编写了一些代码来计算 100! 的结果,但我的函数在 22! 后停止给出正确答案。这是我的代码。作业是计算 100! 的数字之和,但我的代码在 22! 之后给出了错误的答案
/*Calculates the factorial of a given number*/
double factorial(double num);
/*Calculates how many digits are in a number*/
int num_digits(double num);
int main (int argc, char *argv[]) {
double ans = factorial(23);
int num = num_digits(ans);
printf("%lf\n", ans);
printf("%d\n", num);
char x[num];
//convert the number returned by factorial() to a char array
sprintf (x, "%lf", ans);
int i = 0;
int sum= 0;
for (i = 0; i < num; i ++) {
sum += x[i] - '0';
}
printf("--\n%d\n", sum);
return 0;
}
double factorial(double num) {
int i;
double sum = 1;
/*heel simpel, gwn 1 x sum, sum * sum - 1 enz..*/
for (i = num; i > 0; i --) {
sum *= i;
}
return sum;
}
最佳答案
22!大约是10^21,也就是大约2^63。这意味着,你可以算出22!在 64 位机器上使用正常算术,但不能更多,因为那样你会得到整数溢出,结果是垃圾。您必须使用一个特殊的库来提供更大数字的算术。
关于c - 安西C : factorial function wrong a,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16398772/