c程序求∑(n=1,20)n!

来源:百度知道 编辑:UC知道 时间:2024/07/04 23:58:58
答案是
main()
{float s=0,t=1;
int n;
for(n=1;n<=20;n++)
{t*=n;
s+=t;
}
printf("%e\n",s);
}
结果:2.561327e+18
我的第一个程序是:(我是倒着从20!开始算得count表计数,从1到20)
main()
{ int n=20,i;
float t=1,s=0,count=0;
i=n;
while(count<=20)
{
for(;i>=1;i--)
t*=i;
count++;
i=n-count;
s=s+t;
}
printf("%f\n",s);
}
显示:FLOATING POINT ERROR:OVERFLOW,我换了改求∑(n=1,3)n!,发现也是显示结果大于应该的答案。
第二个程序:(和我的程序1思路相似)
main()
{ int n=20,i=20;
float t=1,s=0,count=0;
for(;count<20&&i>=1;count++)
{ t*=i;
i--;
i=n-count;
s+=t;}
printf("%e\n",s);
}运行结果为0
第三个程序:(与第二个程序的区别是一个的i--在for(;;)内,我不知道应该怎么样正确)
main()
{ int n=20,i=20;
float t=1,s=0,count=0;
for(;count<20&&i>=1;count++,i--)
{ t*=i;
i=n-c

//第一个:

while(count<=20)
{
for(i=n-count,t=1;i>=1;i--) t*=i; //每次循环要初始化.你少了t=1这一项.
count++;
s+=t;
}

//第二个:

思路完全错误,没有改的必要.

//第三个:
同第二个.

我不是乱说的.你看我的分析.
你的第一个程序(改后)while循环的前几步,我分解出来,你看就知道了.

第一次:t=20!
s=0+t=20!
第二次:t=19!
s=20!+19!
第三次:t=18!
s=20!+19!+18!
……

我再分析一下答案:(这个是最优的,要学这种思想)
第一次:t=1
s=0+1=1
第二次:t=1*2=2!
s=1+2!
第三次:t=2!*3=3!
s=1+2!+3!
第四次:t=3!*4=4!
s=1+2!+3!+4!
……

你的第二个程序:(我就不厌其烦,帮你解几步吧)
第一次:t=20
s=0+20
i--;//i=19
i=n-count;//i=20
第二次:t=20*20
s=20+20*20
i--;i=n-count;//i=19
第三次:t=20*20*19
s=20+20*20+20*20*19
i=18
第四次:t=20*20*19*18
……
再分析下去我会疯,上面这种方法叫做变量跟踪法,是看看变量在前几个循环有没有按照期望的方式去变化。然后预测以后的步骤。

#include<iostream>
using namespace std;
int main()
{
long long unsigned sum=0,t=1;