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.
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.
#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.
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.
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.
Because of this
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.