求整數1~n之間整數的階乘的和,即是求表達式1!+2!+3!+…+n!的和是多少?
要求:從鍵盤輸入n的值。
源程序代碼參考如下:
using System;
class Class1
{
static void
{
Console.WriteLine("求1~n的階乘之和。");
int n = 0;
long sum = 0;
long fac = 1;
try
{
Console.WriteLine("請輸入n的值:");
n = int.Parse(Console.ReadLine());
for(int i = 1;i<n;i++)
{
fac *= i;
sum += fac;
}
Console.WriteLine("1~{0}的階乘之和為:{1}",n,sum);
}
catch
{
Console.WriteLine("輸入的數字格式不正確!");
}
}
}
運行結果1:
運行結果2:
新聞熱點
疑難解答