because if you use the type double d means 10.78345345345345345
while the float the f means 10.783453453
the compiler never know in the float f if the next digit in 3 is 9 or maybe 2 or 3 or 4
Ps: the float can hold 7 digits decimal while double can hold 15
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
cout << fixed << setprecision(15);
double a = 10.78;
float b = 10.78;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
double c = 10.125;
float d = 10.125;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
// literals
cout << "double: "<< 10.78 << endl;
cout << "float: "<< 10.78f << endl;
}
a = 10.779999999999999
b = 10.779999732971191
c = 10.125000000000000
d = 10.125000000000000
double: 10.779999999999999
float: 10.779999732971191
Internally the values are stored in a binary format. A few numbers such as 1/2 or 1/4 and other powers of two can be stored accurately in floating point format. But in general, the values are approximations. double is more precise than float, so the approximation will be a bit better.
Mostly we should not test floating point values are equal. Instead, do something like this: