求1-20的阶乘之和
知识点:for循环的使用,以及函数的运用
//要求:求1-20的阶乘之和,即1!+2!+3!+……+20!
#include<iostream>
using namespace std;
int main()
{
int i = 1;
float total=0;//注意这里不能声明为int或long型,无法容纳所求结果,要声明为float型
float fac(float);
int n;
cout << "请输入需要求的1-n的阶乘之和的n:";
cin >> n;
for (i; i <= n; i++)
{
total = total + fac(i);
}
cout << "1-" << n << "的阶乘之和为:" << total << endl;
return 0;
}
float fac(float x)
{
float f = 1;
for (int i = 1; i <= x; i++)
{
f = f * i;
}
return f;
}