首页 > 代码库 > 用for和while循环求e的值[e=1+1/1!+1/2!+1/3!+1/4!+1/5!+...+1/n!]

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

/*编写程序,根据以下公式求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;//首项设置为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!]