Comparing floating point numbers
Floating point math is not exact. Simple values like 0.2 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations can change the result. Different compilers and CPU architectures store temporary results at different precisions, so results will differ depending on the details of your environment. If you do a calculation and then compare the results against some expected value it is highly unlikely that you will get exactly the result you intended.
Try this way:
#include<stdio.h> int main() { float a=0.3; float acceptedDiff = 0.0000001; if(fabsf(a-0.3) < acceptedDiff) printf("Hello World!"); else printf("Stack Overflow"); return 0; }
Cbut i'll guess it should be floata==0.3f;ais being promoted todoublesince0.3is a double literal. Since0.3is not exactly representable the comparison fails.(double)(float)(0.3)isn't equal to0.3, because the former has been rounded off tofloatprecision along the way, while the latter retainsdoubleprecision. For an analogy in base 10, suppose I take1/3and represent it to 3 significant figures:0.333. That's the "float"a. Now convert the value ofato a value with 6 significant figures (a "double"):0.333000. That's not equal to0.333333(the value of 1/3 as a "double").