5
#include <iostream>
using namespace std;

int main()
{
    cout.precision(32);

    float val = 268433072;
    float add = 13.5;

    cout << "result =" << (val + add) << endl;
}

我正在用标准编译上述程序g++ main.cc
并运行它./a.out

然而,我收到的输出是,
result =268433088

显然,这不是正确的答案。为什么会这样?

编辑double:使用代替时不会发生这种情况float

4

2 回答 2

10

您可以使用更简单的代码来重现您的“浮动错误”

#include <iostream>
using namespace std;

int main()
{
    cout.precision(32);
    float val = 2684330722;
    cout << "result =" << val << endl;
}

输出

result =2684330752

val如您所见,输出与初始化的值不匹配。

正如已经多次声明的那样,浮点类型的精度有限。您的代码示例只是超出了该精度,因此结果被四舍五入。这里没有“错误”。

于 2013-07-05T18:52:26.590 回答
1

Aside from the reference to (1991, PDF) What Every Computer Scientist Should Know About Floating-Point Arithmetic

The short answer is, that because float has limited storage (like the other primitives too) the engineers had to make a choice: which numbers to store with which precision. For the floating point formats they decided to store numbers of small magnitude precisely (some decimal digits), but numbers of large magnitude very imprecisely, in fact starting with +-16,777,217 the representable numbers are becoming so thin that not even all integers are represented which is the thing you noticed.

于 2013-07-05T18:59:28.087 回答