1
//g++  5.4.0

#include <iostream>

int main()
{
    std::cout << "Hello, world!\n";
    std::cout << (int)0.9999999999999999 << std::endl; // 16 digits after decimal
    std::cout << (int)0.99999999999999999 << std::endl; // 17 digits after decimal
}

输出:

Hello, world!
0
1

为什么会这样?

4

2 回答 2

3

最准确的表示0.999999999999999991.01)
最准确的表示0.99999999999999990.999999999999999888977697537484

1) 以 64 位双精度 IEEE754 浮点表示。

由于没有舍入而是截断,所以当转换为整数类型时,一个给出1,另一个给出。0

于 2018-10-23T06:05:30.190 回答
1

值 0.99999999999999999(小数点后 17 位)的最准确浮点表示正好是 1.0。

值 0.9999999999999999(小数点后 16 位)的最准确浮点表示小于 1.0。

转换为 int 将一个截断为 0,另一个截断为 1。

于 2018-10-23T05:33:54.850 回答