# include <iostream.h> //求1+x1/1!-x2/2!+x/33!-x4/4!+x5/5!-.........
#include <math.h>
double Dowhile( double X) //do while类型求解过程 //求1+x1/1!-x2/2!+x/33!-x4/4!+x5/5!-.........
{
double sum=1,sn=X,n=X,d=1.0,i=1.0;
do {
sum+=sn;
n*=-X;
i++;
d*=i;
sn=n/d;
}while(fabs(sn=(n/d))>=0.0000001);
return sum;
}
double While(double X) // while类型求解过程 //求1+x1/1!-x2/2!+x/33!-x4/4!+x5/5!-.........
{
double sum=1,sn=X,n=X,d=1.0,i=1.0;
while(fabs(sn=(n/d))>=0.0000001)
{
sum+=sn;
n*=-X;
i++;
d*=i;
sn=n/d;
}
return sum;
}
double For(double X) // for类型求解过程 //求1+x1/1!-x2/2!+x/33!-x4/4!+x5/5!-.........
{
double sum=1,sn=X,n=X,d=1.0;
for(int i=1; fabs(sn=(n/d))>=0.0000001;i++)
{
sum+=sn;
n*=-X;
d*=i;
sn=n/d;
}
return sum;
}
void main()
{
double x,s1,s2,s3;
cout<<"please input x:\n";
cin>>x;
s1=Dowhile(x);
s2=While(x);
s3=For(x);
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
}
我输入1则显示 1.632..
1.632....
1.367...
我分析了好厂时间分析不出来,大家给指点为何for循环与其他的结果不一样!
[此贴子已经被作者于2006-7-15 17:05:31编辑过]