Factorial summation C language realizes the sum of factorials and three methods to realize the first factorial and then accumulation

topic:

The title here is an example of the sum of factorials from 1-20

Method 1: Use a layer of for loop to realize the code is simple, fast and easy to understand

The code example is as follows:

#include<stdio.h>
int main()
{
	double a = 1, sum = 0;//因为最后值可能会超出int所能接收的范围 故用double
	int n, i;
	scanf("%d", &n);//注意scanf_s和scanf的使用场景
	for (i = 1; i <= n; i++)
	{
		a = a*i;
		sum = sum + a;
	}
	printf("%lld", sum);//double的输入格式要对
	return 0;
}

The result of the operation is as follows:

Method 2: Use two layers of for loop nesting

The code example is as follows:

//需要注意对于1-20阶乘结果已经超出了int能够接收的范围
//   故用double类型
//1.遍历获取每一个数字[1-20]
//2.对每一个数进行阶乘
//3.对每个数字的阶乘结果进行求和
int main()
{
    double total_sum = 0.0;
    for (int i = 1; i <= 20; i++)//i控制求和
    {
        //i=8  ---> 8*7*6*....*1
        double single_num = 1.0;
        for (int j = i; j > 0; j--)
        {
            single_num *= j;//j控制阶乘
        }
        total_sum += single_num;
    }
    printf("%lf\n", total_sum);
    return 0;
}

The result of the operation is as follows:

 

Method 3: Function recursive implementation

#include<stdio.h>
long int fac(unsigned int n)  //定义为long int 型,避免溢出
{
    long int f;
    if (n == 0) return;        //当n=0是,递归法到尽头,依次返回函数值。
    f = fac(n - 1) * n;
    return (f);               //返回最后一次函数值,即单次阶乘的最后结果
}

int main()
{
    unsigned int n;
    long int s =0;
    int i;
    scanf_s("%d", &n);//此处注意scanf_s与scanf的使用场景
    for (i = 1; i <= n; i++)  s += fac(i);    //以循环控制阶乘的和。fac函数每一次的返回值作为s的自加值
    printf("%ld", s);
    return 0;
}
#include<iostream>
#include<cmath>

double fac(double t)
{
    if (t == 1)
        return 1;
    else
        return  t * fac(t - 1);
}

int main()
{
    using namespace std;
    double i, n, sum = 0;
    cin >> n;
    if (n > 14)
        return 0;
    for (i = 1; i < n; i++)
    {
        double b = fac(i);
        sum += b;
    }
    cout << "sum =" << sum << endl;
    printf("%lf\n", sum);
    return 0;
}

The result of running the code is as follows:

 

Editor's note: The above-mentioned various methods of writing code for this topic are welcome to collect, learn from and forward;

               The above code is for reference only, if you have any questions, you are welcome to criticize and correct in the message area;

               All rights reserved, reprints must be investigated, any similarity is purely coincidental, please indicate the source for reprinting.

               By CRH380AJ2808 2022.04.26
————————————————


Copyright statement: This article is an original article of CSDN blogger "CRH380AJ2808", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/JH13thpig/article/details/124361837

Guess you like

Origin blog.csdn.net/JH13thpig/article/details/124434094