我想学习一些C编程,并测试我的基本技能,我正在计算一个简单的计算因子。但是,不给出120的正确答案5的阶乘,它给出了-1899959296。怎么了?这里是我的代码如下:为什么这个阶乘计算不正确?
#include <stdio.h>
int factorial(int x)
{
int i;
for(i=1; i < x; i++)
x *= i;
return x;
}
int main()
{
int a = 5, b;
b = factorial(a);
printf("The factorial of %d is %d \n", a, b);
return 0;
}
在此先感谢!
假装你是一台计算机,并尝试一步一步运行它,x = 2(或3)。或者,在调试器中运行它。 – user31264
请参阅[**如何调试小程序**](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)并与鸭子交谈...真的,它帮助':)' –
作为提示:看看循环绑定。 – templatetypedef