我无法使以下代码正常工作。
#include <stdio.h>
// I am not sure whethere I should void here or not.
int main() {
// when the first bug is solved, I put here arg[0]. It should be
// similar command line parameter as args[0] in Java.
int a=3;
int b;
b = factorial(a);
// bug seems to be here, since the %1i seems to work only in fprintf
printf("%1i", b);
return 0;
}
int factorial(int x) {
int i;
for(i=1; i<x; i++)
x *= i;
return x;
}
如何让代码工作?
最佳答案
您正在修改循环内的循环终止变量 (x)。目前,当 x 溢出 32 位整数的范围,然后变为负数且非常大时,您的代码在几次迭代后就会崩溃,从而终止循环。
应该是:
int factorial(int n) {
int i, x = 1;
for (i = 2; i <= n; ++i) {
x *= i;
}
return x;
}
更好的是,对于变量 x
和返回值,您应该使用 long
而不是 int
,因为 n! 很快变得非常大。
关于c - 无法使阶乘函数在 C 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/843188/