While many people will tell you to always compare floating point numbers with an epsilon (and it's usually a good idea, though it should be a percentage of the values being compared rather than a fixed value), that's not actually necessary here since you're using constants.
Your specific problem here is that:
float a = 0.7;
uses the double constant 0.7
to create a single precision number (losing some precision) while:
if (a == 0.7)
will compare two double precision numbers (a
is promoted first).
The precision that was lost when turning the double 0.7
into the float a
is not regained when promoting a
back to a double.
If you change all those 0.7
values to 0.7f
(to force float rather than double), or if you just make a
a double, it will work fine - I rarely use float
nowadays unless I have a massive array of them and need to save space.
You can see this in action with:
#include <stdio.h>
int main (void){
float f = 0.7; // double converted to float
double d1 = 0.7; // double kept as double
double d2 = f; // float converted back to double
printf ("double: %.30f\n", d1);
printf ("double from float: %.30f\n", d2);
return 0;
}
which will output something like (slightly modified to show difference):
double: 0.6999999|99999999955591079014994
double from float: 0.6999999|88079071044921875000000
\_ different beyond here.