【发布时间】:2015-10-25 11:28:06
【问题描述】:
如何显示for 循环后的最后一个数字?
本程序用于计算欧拉法
-
xO我输入 0 -
yO我输入 1 -
send我输入 1
我尝试在x=1.0 时获取y 的最后一个值,但现在无法完成。
float num,xO,yO,xend,x,y,delx,func,exact,diff;
char next ='y';
while( next =='y') {
cout << "Please enter the method of choice;press 1 for Euler's Method,"<< endl;
cout << "press 2 for Heun's Method:";
cout <<setiosflags(ios::showpoint);
cin >> num;
if ( num==1 ) {
cout <<"Solution for the equation dy/dx = f(x) by Euler's Method"<< endl;
cout <<"Enter the initial condition xO :";
cin >> xO;
cout <<"Enter the initial condition yO :";
cin >> yO;
cout <<"Enter the final value of x :";
cin >> xend;
cout <<"Enter the step size delta_x :";
cin >> delx;
y=yO;
for ( x=xO; x <=1.00000016; x+=delx ) {
cout<<setw(10)<<setiosflags(ios::left)<<setprecision(2)<<x<<setw(10)<<setiosflags(ios::left)<<setprecision(6)<<y<<endl;
func=4*x*y;
func=sqrt(func);
y=y+((delx)*(func));*//the last y is 2.54052
}
cout<<"\nThe solution y10 at x=1 is "<<y<<endl;
}
我想显示的数字是 2.54052,但现在是 2.85930。我应该如何纠正这个问题?
【问题讨论】:
-
float 类型的数字总是有些不精确,不适合 for 循环。
-
不要继续添加,你会越来越不准确。相乘。