C Program: Sum of Factorials

Here is a C code example that calculates the factorial sum using functions.

#include <stdio.h>

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

// 计算阶乘之和的函数
int sumOfFactorials(int num) {
    int sum = 0;
    for (int i = 1; i <= num; i++) {
        sum += factorial(i);
    }
    return sum;
}

int main() {
    int n;
    printf("请输入一个数n:");
    scanf("%d", &n);
    int result = sumOfFactorials(n);
    printf("1! + 2! + ... + %d! = %d\n", n, result);
    return 0;
}

Within the code above, the factorial() function is utilized to calculate the factorial of a number, while the sumOfFactorials() function is used to calculate the sum of factorials. The main() function is responsible for receiving user input for a number ‘n’ and printing the result of 1! + 2! + … + n!.

bannerAds