阶乘之和c++语言程序
时间: 2023-11-18 13:05:28 浏览: 84
对数进行阶乘求和(C语言程序)
Sure! Here's a C++ program to calculate the sum of factorials:
```cpp
#include <iostream>
// Function to calculate factorial
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num;
int sum = 0;
std::cout << "Enter a number: ";
std::cin >> num;
for (int i = 1; i <= num; i++) {
sum += factorial(i);
}
std::cout << "The sum of factorials up to " << num << " is: " << sum << std::endl;
return 0;
}
```
In this program, we define a `factorial` function to calculate the factorial of a number. We then prompt the user to enter a number and use a loop to calculate the sum of factorials up to that number. Finally, we output the result.
阅读全文