【问题标题】:Can't display the last number after the for loopfor循环后无法显示最后一个数字
【发布时间】: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。我应该如何纠正这个问题?

【问题讨论】:

标签: c++ loops for-loop


【解决方案1】:

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

例如,不要使用“float x

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

float func = static_cast<float>(4 * x * y) / 100000000; 

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2017-03-31
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2015-06-17
    相关资源
    最近更新 更多