pta Exercises 2-6 Find the sum of the first N terms of the factorial sequence (15 points)

Topic Collection of Zhejiang University Edition "C Language Programming (3rd Edition)"

Exercise 2-6 Find the sum of the first N terms in the factorial sequence (15 points)

This question requires writing a program to calculate the sum of the first N items of the sequence 1!+2!+3!+...

Input format:

Enter a positive integer N not exceeding 12 in one line.

Output format:

Output integer results in one line.

Input sample:

5

Sample output:

153

Code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    
    
    int N,S1=1,S=0;
    scanf("%d",&N);
    for (int j=N; j>=1; j--)
    {
    
    
            S1=1;
        for (int i=j; i>=1; i--)
        {
    
    
            S1*=i;
        }
        S=S+S1;

    }
    printf("%d",S);
    return 0;
}

to sum up:

 for (int j=N; j>=1; j--)
    {
    
    
         S1=1;
        for (int i=j; i>=1; i--)
        {
    
    
            S1*=i;
        }
        S=S+S1;
    }

The outer loop is the number of control loops, and the inner for loop is used to find the factorial. After each factorial addition is calculated, S1 is defined as 1 through the external assignment to store the next factorial result.

Guess you like

Origin blog.csdn.net/crraxx/article/details/109132677