输入下面的代码并保存为factorial.c:
/*计算1! + 2! + 3! + ... +100!的值*/ #include <stdio.h> double factorial(int a); //函数声明,详细代码往下看 int main() { int i; double sum = 0; for (i = 1; i <= 100; i++) sum += factorial(i); printf("1! + 2! + 3! + ... +100! = %e\n", 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