编写c++程序。按下面的公式求sum的值。sum=1!+2!+3!+4!+5!
时间: 2024-04-15 16:21:19 浏览: 95
c++ 1!+2!+3!+..
以下是一个C++程序,用于按照给定公式计算sum的值:
```cpp
#include <iostream>
using namespace std;
int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int main() {
int n;
double sum = 0;
cout << "输入n: ";
cin >> n;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
cout << "sum = " << sum << endl;
return 0;
}
```
阅读全文