我想學習一些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