Can anyone explain why these two variable of the same value can output different values when i use setprecision()?
#include <iostream>
#include <iomanip>
int main()
{
float a=98.765;
double b = 98.765;
//std::cout<<std::setprecision(2)<<a<<std::endl;
std::cout<<std::fixed;
std::cout<<std::setprecision(2)<<a<<std::endl;
std::cout<<std::setprecision(2)<<b<<std::endl;
}
The output for a will be 98.76 while the output for b will be 98.77.
Those variables don't have the same value. When you shoehorn the literal double
of 98.765
into the float, it has to do a best fit, and some precision is lost.
You can see this quite easily if you change the precision to 50, you'll also see that not even the double can represent that value exactly:
98.76499938964843750000000000000000000000000000000000
98.76500000000000056843418860808014869689941406250000
However, the important thing is that the former float
variable will round down, the latter double
will round up.
See also the IEEE754 online converter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With