setprecision 和浮点

setprecision and floating point

提问人:SRYZDN 提问时间:1/21/2015 更新时间:1/21/2015 访问量:1012

问:

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

Desired output:
Car     Hours    Charge
1        1.5      2.00
2        4.0      2.50
3       24.0     10.00

但结果如下:

Actual output:
Car     Hours    Charge
1        2       2
2        4       2.5 
3    2e+01      10

欢迎任何可以指导我使用正确的浮点比较和正确使用 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;

}
C++ 浮点精度

评论

0赞 SRYZDN 1/21/2015
我在代码块中运行了代码。我只是在学习浮点和set精度的调整

答:

1赞 Hiperon43 1/21/2015 #1

您需要函数来使 cout 写入数字,当它只有“0”时。fixed

所以像这样使用它:

cout << fixed;
cout<<i+1<<setw(10)<<setprecision(1)<<hour[i]<<setw(10)<<setprecision(2)<<charge[i]<<endl;
6赞 Sander De Dycker 1/21/2015 #2

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

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

std::cout << std::fixed << std::setprecision(2) << 24.0;

将显示:

24.00

评论

0赞 Hiperon43 1/21/2015
我怎样才能将固定形式恢复到标准输出?
1赞 Sander De Dycker 1/21/2015
@user3895596 :您可以使用 std::d efaultfloat 返回到默认的浮点格式。