C++ different output in double and float
This question already has an answer here:
33.3 has no exact bounded binary representation, so converting it to float
or double
incurs in rounding.
float
has a 23 bit mantissa, equivalent to 6.92 decimal digits of precision; there you are asking to print 8 digits, which are more than the available precision, and thus will show the effect or the rounding.
double
instead has a 52 bit mantissa, which is equivalent to 15.65 decimal digits; the 8 significant digits print holds well, as you are still printing good digits, unaffected by the rounding.
To make an easier to digest example in our beloved base 10: imagine you had a decimal data type with 15 digits of precision, and you want to store 1/3 in it. The best you can do is to store 0.333333333333333; them you copy it into a data type with 6 digits of precision: it becomes 0.333333.
Now, if you print the first value with 8 decimal digits you get 0.33333333, while for the second one you have 0.33333300 - as you already lost the other digits in the conversion.
That is what is happening here, but with binary floating point instead of decimal.
Here is a good answer to the difference of float vs. double.
What is the difference between float and double?
By default, any magic number (as 33.30 in your program) is processed as double. when you do float a = 33.30;
, an error occurred.
上一篇: 浮点精度是可变的还是不变的?