求阶乘之和(循环)c++
时间: 2024-12-06 17:27:29 浏览: 213
在C++中计算一个整数范围内所有正整数的阶乘之和,通常会采用循环结构结合递归的方式来实现,因为求阶乘的过程本身就适合用递归描述。这里是一个简单的示例代码:
```cpp
#include <iostream>
using namespace std;
unsigned long long factorial(int n) {
if (n == 0 || n == 1) // 阶乘的基本情况,0和1的阶乘都是1
return 1;
else
return n * factorial(n - 1); // 递归调用,计算n-1的阶乘然后乘以n
}
int sum_of_factorials(int limit) {
unsigned long long sum = 0; // 初始化总和为0
for (int i = 1; i <= limit; ++i) {
sum += factorial(i);
}
return sum;
}
int main() {
int number_limit;
cout << "请输入一个正整数作为上限: ";
cin >> number_limit;
cout << "从1到" << number_limit << "的所有正整数阶乘之和是: " << sum_of_factorials(number_limit) << endl;
return 0;
}
```
在这个程序中,`factorial`函数用于计算单个数字的阶乘,而`sum_of_factorials`函数则通过for循环遍历指定范围内的每个整数,并将它们的阶乘累加到总和`sum`中。
阅读全文
相关推荐















