c++ - 为什么 1.999(共16个9) 转换成 int 是 2,1.9 转换成 int 是 1?
怪我咯
怪我咯 2017-04-17 13:46:37
0
2
453

《C++ Primer》第五版,中文版。p33。
1.999999999999999(比转换之后少是 2 的少个 9) 也是 1。
微软免费 IDE 2015。g++ 好像也一样。

#include <iostream>
using namespace std;

int main()
{
    double d = 1.9999999999999999;
    int i = d;
    cout << i << endl;

    return 0;
}
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
大家讲道理

Now, if you have learned C language well enough, you should know that the precision of double type is 15 digits after the decimal point, and if you write 16 digits, the compiler will think you The entered value is invalid and will be automatically converted to 2.0 for you.
According to the instruction specification of floating point conversion to integer, 1.x is always 1 after conversion. Similarly, 2.0 is naturally 2.

Supplement

Essentially, you can write a program yourself and then right-click to assemble it. It’s a very simple question.
I will add the assembly code to make it clearer.

  1. When there are 15 9s, the value here in the compiled code is 0x3ffffffffffffffb

  2. When there are 16 9s, the compiled code is directly 0x4000000000000000, which is 2.0

That is, this process is only optimized by the editor.

小葫芦

Because of this

#include <iostream>
using namespace std;

int main()
{
    double d = 1.9999999999999999;
    int i = d;
    cout <<"d = "<< d<<"\ni = "<< i << endl;

    return 0;
}

Run it and see what the output is.
Because floating point numbers cannot accurately represent all numbers, some numbers can only be saved approximate values. 1.9999999999999999 here will save its approximate value 2.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template