using namespace std;
int main()
{
float f1 = 5488955, f2 = 0.2197265620, f3 = 0;
f3 = f1 + f2;
f3 = f3 - f1;
cout << f3<<endl;
return 0;
}
why f3 value getting printed as 0 but not 0.2197265620
using namespace std;
int main()
{
float f1 = 5488955, f2 = 0.2197265620, f3 = 0;
f3 = f1 + f2;
f3 = f3 - f1;
cout << f3<<endl;
return 0;
}
why f3 value getting printed as 0 but not 0.2197265620
The IEEE-754 floating point format has limited precision. Double-precision floating point numbers have more precision than single-precision floating point numbers, as they use 64 bits instead of only 32 bits.
The floating-point number 5488955.2
cannot be represented in a single-precision floating point number. The closest numbers it can represent are 5488955.0
and 5488955.5
. It is therefore rounded down to 5488955.0
. In order to prevent this rounding, you must use double-precision floating point numbers, by using the data type double
instead of float
.
However, with very high numbers, you will sooner or later have the same problem with double
. Therefore, if you require arbitrary precision, you cannot use float
or double
, but must use a special arbitrary precision software library. But for most cases, double
should be sufficient.
Consider switching to doubles. If you change the float to a double it would work. In C++ I recommend using doubles because in some cases floats are broken.