设定精度和浮点数

SRY*_*ZDN 2 c++ floating-point-precision

运行以下代码,我希望收到这样的输出:

Desired output:
Car     Hours    Charge
1        1.5      2.00
2        4.0      2.50
3       24.0     10.00
Run Code Online (Sandbox Code Playgroud)

但是结果如下:

Actual output:
Car     Hours    Charge
1        2       2
2        4       2.5 
3    2e+01      10
Run Code Online (Sandbox Code Playgroud)

欢迎提供任何可以指导我使用正确的浮点比较和正确使用setprecision的建议

int main()
{
    double hour[3];
    double charge[3];

    double sum_hour = 0;
    double sum_charge = 0;

    for (int i = 0; i < 3; i++)
    {
        cout<<"Enter the hours for car No. "<<i<<": ";
        cin>>hour [i];

        if (hour [i] <= 3)
            {charge [i] = 2.00;}
        if (hour [i] > 3 && hour [i] < 24)
            {charge [i] = (2.00 + (ceil(hour [i] -3))*0.5);}
        if (hour [i] == 24)
            {charge [i] = 10.00;}

        sum_hour  = sum_hour + hour [i];
        sum_charge = sum_charge + charge [i];
    }

    cout<<"Car"<<setw(10)<<"Hours"<<setw(10)<<"Charge"<<endl;

    for (int i = 0; i < 3; i++)
    {
        cout<<i+1<<setw(10)<<setprecision(1)<<hour[i]<<setw(10)<<setprecision(2)<<charge[i]<<endl;
    }
    cout<<"TOTAL"<<setw(6)<<sum_hour<<setw(10)<<sum_charge<<endl;

}
Run Code Online (Sandbox Code Playgroud)

San*_*ker 5

std::setprecision 默认情况下,设置显示的有效位数总数(即,包括小数点前的位数)。

要设置小数点后显示的位数,请使用std::fixed

std::cout << std::fixed << std::setprecision(2) << 24.0;
Run Code Online (Sandbox Code Playgroud)

将显示:

24.00
Run Code Online (Sandbox Code Playgroud)