用C语言编写程序:20∑n=1(n!),即1!+2!+3!+……+19!+20!(从1的阶乘一直加

2025-01-01 19:17:06
推荐回答(3个)
回答1:

#include

double factorial(int n);//函数声明

int main( )
{
int i = 0;
const int MAX_NUM = 20;
double sum = 0;

//求1!+2! +...+20!
for (i=1; i<=MAX_NUM; i++)
sum = sum + factorial(i);

printf("1!+...+%d!=%.0f\n",MAX_NUM, sum);//输出结果信息
}
//求阶乘函数的定义,20!的阶乘很大,需要用浮点数返回类型
double factorial(int n)
{
int i=0;
double s=1.0; //存放阶乘n!的乘积
if ( n<1 ) return -1;//参数不对,返回负数
for ( i=1; i<=n; i++ )
{
s = s*i;
}
return s;
}

//纯手工敲入,并运行验证,请给分,谢谢

回答2:

void main(){
int n=1,sum=1;
while(n<=20){
sum=sum+sum*n;
n++;
}
printf("sum=%d",sum);
}

回答3:

#include "stdio.h"
#define NUM 20
int main()
{
int sum = 0;
int sumTmp = 0;
for (int i=1; i<=NUM; i++)
{
sumTmp = 1;
for (int j=1; j<=i; j++)
{
sumTmp = sumTmp*j;
}

sum = sum + sumTmp;
}

printf("%d\n", sum);
return 0;
}