用C与Python计算1! + 2! + 3! + ... +100!的值

方法一、调用函数

输入下面的代码并保存为factorial.c:

/*计算1! + 2! + 3! + ... +100!的值*/
#include <stdio.h>
#define MAX 100
double factorial(int a); //函数声明,详细代码往下看

int main()
{
    int i;
    double sum = 0;
    for (i = 1; i <= MAX; i++)
        sum += factorial(i);
    printf("1! + 2! + 3! + ... +100! = %e
", sum);
    return 0;
}

double factorial(int a)
{
    double fact = 1;
    for (int i = 1; i <= a; i++) {
    //这里for循环也可以使用: for (int i = a; i >= 2; i--)
        fact *= i;
    }
    return fact;
}

编译并执行:

gcc factorial.c && ./a.out

结果为:

1! + 2! + 3! + ... +100! = 9.426900e+157

Python代码:

# 1! + 2! + 3! + ... + 100! =

def factorial(n):
    fact = 1
    for i in range(1, n+1):
        fact *= i
    return fact

s = 0
for i in range(1, 101):
    s += factorial(i)
print(f"s={s}")

输出结果:

s=94269001683709979260859834124473539872070722613982672442938359305624678223479506023400294093599136466986609124347432647622826870038220556442336528920420940313

如果把

print(f"s={s}")

改为

print("s=%e"%s)

输出结果为:

s=9.426900e+157

与C的结果一致

二、循环嵌套法:

// 使用循环嵌套的方式计算1!+2!+3!+...100!
#include <stdio.h> #define MAX 100 int main() { double sum=0; int i, j; for (i=1; i<=MAX; i++) { //接下来,思考:如何在这个for循环里面把每个阶乘都计算出来 double s=1; for (j=1; j<=i; j++) { s = j*s; } sum += s; } printf("sum=%le ",sum); return 0; }

输出结果:

sum=9.426900e+157
原文地址:https://www.cnblogs.com/profesor/p/12782158.html