《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;
}
大家讲道理2017-04-17 13:48:37
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.
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.
When there are 15 9s, the value here in the compiled code is 0x3ffffffffffffffb
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.
高洛峰2017-04-17 13:48:37
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.