2

我以前从未真正使用过花车,而我正在从事的当前项目需要它们。我遇到了几年前了解到的奇怪问题,但已经忘记了为什么会发生这种情况。

我乘以或添加浮点数后的结果不是他们应该的。

这是我的代码:

void main ()
{
    //Example 1 - ERROR
    float a=16937.6;
    float b=112918;
    float total=b+a;
    cout<<total<<endl; //Outputs 129896 - rounds up and loses decimal (129855.6)

    //Example 2 - Error
    float c=247.82;
    float d=9995.2;
    float total2=c+d;
    cout<<total2<<endl; //Outputs 10243 - loses all decimals (10243.02)
    system ("pause");

}
4

2 回答 2

7

您的问题不是小数精度 - 它是用于输出值的格式。

尝试:

cout << setiosflags(ios::fixed) << setprecision(2) << x;
于 2012-02-29T21:26:43.517 回答
4

每个程序员都应该知道的关于浮点运算的知识,或者为什么我的数字不加起来?

简而言之,实数是无限的,计算机不是。

于 2012-02-29T21:22:32.067 回答