得到的結(jié)果如圖!//1.做一個函數(shù)體static int F(int n) { int sum = 1; for (int i = 1; i <= n; i++) { sum *= i; } return sum; }主函數(shù)內(nèi)寫:int sum = 0; for (int i = 1; i <= 20; i++) { sum += F(i); Console.WriteLine(i + "積乘的和是:" + sum); } //Console.WriteLine(i+"積乘的和是:"+sum); Console.ReadKey();得到的結(jié)果如圖!在網(wǎng)上找了好些代碼,結(jié)果依然一樣,求大神指點!
1 回答

慕妹3146593
TA貢獻1820條經(jīng)驗 獲得超9個贊
int所能表示的最大值為2147483647,而20!的結(jié)果超出了int所能表示最大值。因此,在計算階乘時,采用long。代碼如下:
123456789101112131415161718192021222324252627 | using System; class Program { static void Main( string [] args) { long result = 0; for ( int i = 1; i <= 20; i++) { long item = Factorial(i); Console.WriteLine( "{0}!={1}" , i, item); result += item; } Console.WriteLine( "1!+2!+3!+...+20!={0}" , result); Console.ReadKey(); } public static long Factorial( int n) { long r = 1; for ( int i = 1; i <= n; i++) { r *= i; } return r; } } |
- 1 回答
- 0 關(guān)注
- 1984 瀏覽
添加回答
舉報
0/150
提交
取消