Sum of Factorials in C++: Explained with Code

To calculate the sum of factorials, first calculate the factorial of each number, then add them together. Here is an example code using the C++ programming language to calculate the sum of factorials:

#include <iostream>

// 计算阶乘的函数
int factorial(int n) {
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

int main() {
    int n, sum = 0;
    std::cout << "Enter a number: ";
    std::cin >> n;

    for (int i = 1; i <= n; i++) {
        sum += factorial(i);
    }

    std::cout << "Sum of factorials from 1 to " << n << " is: " << sum << std::endl;

    return 0;
}

In this example, we first define a function called factorial to calculate factorials. Then in the main function, we take the user input number n and use a loop to calculate the factorial of each number from 1 to n, adding them together. Finally, we output the result.

bannerAds