求连续整数阶乘的和

#include <stdio.h>

long sum(int n)
{
    long sum = 0, fact = 1;
    
    for(int i = 1; i <= n; i++)
    {
        fact *= i;
        sum += fact;
    }
    
    return sum;
}


int main(void)
{
    int n;
    
    printf("n(3-20):");
    scanf("%d", &n);
    if(n < 3 || n > 20)
        return 0;
    
    printf("1! + 2! + 3! + ... + %d! = %ld\n", n, sum(n));
    
    return 1;
}

测试结果:

gcc test.c -o test

./test
n(3-20):5
1! + 2! + 3! + ... + 5! = 153

猜你喜欢

转载自blog.csdn.net/xiezhi123456/article/details/86151304
今日推荐