用for和while迴圈求e的值[e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!],while

來源:互聯網
上載者:User

用for和while迴圈求e的值[e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!],while

/*編寫程式,根據以下公式求e的值。要求用兩種方法計算:1)for迴圈,計算前50項2)while迴圈,直至最後一項的值小於10-4e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!*/#include<stdio.h>//=====================================================//用for求e的值double For(){double sum=1,temp=1;int i;for(i=1;i<50;i++){temp/=i;sum+=temp;}return sum;}//=====================================================//用while迴圈求e的值double While(){double sum=1;//首項設定為1double temp = 1;int i=1;while(temp>=1e-4){//【e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!】temp = temp/i;//第二項1/1,即1/1!;第三項1/2,即1/2!;第四項(1/2)/3,即1/3!...sum = sum+temp;i++;}return sum;//返回sum}//主函數int main(){double a = For();double b = While();printf("用for迴圈求出e的前50項的和是%lf\n",a);printf("用while迴圈求出e和是%lf\n",b);return 0;}


編寫程式,e的值e≈1+1/1+1/2!+1/3!+1/4!+···+1/n! (1)用for迴圈,計算前50項 (2)用while迴圈

(1)
#include <stdio.h>

void main()
{
int n=1;
float i=1,e=1;
for(n=1;n<=50;n++)
{
i=i*n;
e=e+1/i;
}
printf("%f",e);
}
(2)
#include <stdio.h>
void main()
{
int n=1;
float i=1,e=1;
while(1/i>10e-4)
{
i=i*n;
e=e+1/i;
n++;
}
printf("%f",e);
}
 
e=1+1/1!+1/2!+1/3!+1/4!+…… 1用for迴圈,計算前50項 2用while迴圈要直至最後一項小於10的-6次

while語句迴圈的錯誤,t真的是按照1/1!,1/2!,1/3!這樣變的嗎?照你這樣定義,第一迴圈t=1沒錯,第二迴圈,t++(t=2),t*=t(t=4),t=1/t(t=0.25),也不等於1/2!(0.5)啊。本身的演算法就是錯誤的。 至少還應該再定義一個變數來表示後面每一項的分母。
for語句迴圈的錯誤,既未定義e的初始值,t也不是按照1/1!,1/2!,1/3!這樣變的。

參考:
#include <stdio.h>
#include <math.h>
int f(int n)
{
long k=1;int i;
for(i=1;i<=n;i++)
k=k*i;
return k;
}
main()
{
float e=1,t;
int m=1;
while(fabs(t)>=1e-6)
{
t=1.0/f(m++);
e+=t;
}
printf("e=%f",e);
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.