实验10-3 递归求阶乘和 (15 分)
1. 题目摘自
https://pintia.cn/problem-sets/13/problems/575
2. 题目内容
本题要求实现一个计算非负整数阶乘的简单函数,并利用该函数求 1!+2!+3!+...+n! 的值。
函数接口定义:
double fact( int n );
double factsum( int n );
函数fact应返回n的阶乘,建议用递归实现。函数factsum应返回 1!+2!+...+n! 的值。题目保证输入输出在双精度范围内。
输入样例1:
10
输出样例1:
fact(10) = 3628800
sum = 4037913
输入样例2:
0
输出样例2:
fact(0) = 1
sum = 0
3. 源码参考
#include <iostream>
#include <iomanip>
using namespace std;
double fact( int n );
double factsum( int n );
int main()
{
int n;
cin >> n;
cout << fixed << setprecision(0);
cout << "fact(" << n << ") = " << fact(n) << endl;
cout << "sum = " << factsum(n) << endl;
return 0;
}
double fact( int n )
{
int i;
double s;
s = 1;
for(i = 1; i <= n; i++)
{
s *= i;
}
return s;
}
double factsum( int n )
{
int i;
double s;
s = 0;
for(i = 1; i <= n; i++)
{
s += fact(i);
}
return s;
}