无法显示 for 循环后的最后一个数字

Can't display the last number after the for loop

本文关键字:最后一个 数字 循环 显示 for      更新时间:2023-10-16

如何显示for循环后的最后一个数字?

该程序用于计算欧拉法

  • 对于xO,我输入0
  • yO输入1
  • send I输入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。我该如何纠正这个问题?

在循环的条件部分使用整数而不是浮点数。

例如,用"int x <= 100000016"代替"float x <=1.00000016",这样不会丢失精度。

然后,将循环的花括号内的值除以1e8,并显式地将它们转换为float类型。

float func = static_cast<float>(4 * x * y) / 100000000; 
相关文章: