求1!+3!+5!+……+n!的和,要求用循环嵌套设计,n<12。用C++
时间: 2024-04-28 12:17:13 浏览: 85
SQLiteC++.pdf
求1!+3!+5!+……+n!的和,可以使用循环嵌套的方式来设计。以下是用C++实现的代码:
```cpp
#include <iostream>
using namespace std;
int factorial(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
int main() {
int n;
cout << "请输入n的值(n<12):";
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i += 2) {
sum += factorial(i);
}
cout << "求和结果为:" << sum << endl;
return 0;
}
```
阅读全文