用for和while循環求e的值[e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!]
/*編敲代碼,依據下面公式求e的值。要求用兩種方法計算: 1)for循環。計算前50項 2)while循環,直至最後一項的值小於10-4 e=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;//首項設置為1 double 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; }
用for和while循環求e的值[e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!]