習(xí)題10-2 遞歸求階乘和 (15 分)
1. 題目摘自
https://pintia.cn/problem-sets/12/problems/352
2. 題目?jī)?nèi)容
本題要求實(shí)現(xiàn)一個(gè)計(jì)算非負(fù)整數(shù)階乘的簡(jiǎn)單函數(shù),并利用該函數(shù)求 1!+2!+3!+...+n! 的值孽亲。
函數(shù)接口定義:
double fact( int n );
double factsum( int n );
函數(shù)fact應(yīng)返回n的階乘,建議用遞歸實(shí)現(xiàn)盾戴。函數(shù)factsum應(yīng)返回 1!+2!+...+n! 的值诽嘉。題目保證輸入輸出在雙精度范圍內(nèi)挺举。
輸入樣例1:
10
輸出樣例1:
fact(10) = 3628800
sum = 4037913
輸入樣例2:
0
輸出樣例2:
fact(0) = 1
sum = 0
3. 源碼參考
#include <iostream>
double fact(int n);
double factsum(int n);
int main()
{
int n;
scanf("%d", &n);
printf("fact(%d) = %.0f\n", n, fact(n));
printf("sum = %.0f\n", factsum(n));
return 0;
}
double fact(int n)
{
double s = 1;
if ((n == 0) || (n == 1))
{
return 1;
}
else
{
return n*fact(n - 1);
}
}
double factsum(int n)
{
double s = 0;
for (int i = 1; i <= n; i++)
{
s += fact(i);
}
return s;
}