c++ - 设置精度和 float

标签 c++ floating-point-precision

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

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

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

}

最佳答案

std::setprecision默认设置显示的有效数字总数(即包括小数点前的数字)。

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

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

将显示:

24.00

关于c++ - 设置精度和 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28066919/

相关文章:

c++ - OpenGL 索引数组

c++ - QT - 取消选中复选框

c++ - float、double 和 long double 是否有保证的最小精度?

Java float 比 double 更精确?

c++ - C 到 C++ : Transitioning from one language to the other

c++ - 从线程执行的函数返回结构数组

c++ - vs2010编译的MFC app在win2k下运行

特定数字范围之间的 Javascript Math.floor 问题

php - 为什么两个具有 PHP_INT_MAX 值的浮点变量是相同的,除非其中之一的值大于 1025

c - 真正基本的 mpir 问题