You're a victim of
precision error.
There are two things you need to consider.
First, when you write: 0.3 this literal is assumed to a
double. Not float.
If you want float literals you should use: 0.3f
Second, you're almost certain to get false if you compare double and a float using == .
This is because of differences in precision. To see it in action compare the outputs of the following:
1 2
|
printf("%.20f\n", 0.3f); //0.30000001192092896000
printf("%.20lf\n", 0.3); //0.29999999999999999000
|
1 and 0 are different in this regard because they are "well behaved" and so are all numbers which can be written in binary form with finite number of digits. e.g. 0.5f == 0.5 will yield true. For almost every other number though (there are a lot more pathological than well behaved numbers) you ought to get false after doing such a comparison
In general, you must never use == between float or double types (let alone mix them together!)
Instead, if you wanted to compare if two floating point values are "equal" you should use something like the following:
1 2
|
#define M_PREC 0.0001
#define fcmp(x, y) (fabs(x - y) < M_PREC)
|
That is, you should only consider them "equal" up to M_PREC.
You might think this is cumbersome, but that's how it's done.