+ 4
Can any one explain why we got this kind of output and also say me when " float is true " and "double is false" gets printed ?
#include<stdio.h> int main() { float i =0.1; double j =0.1; if(i == 0.1) puts("float is true\n"); else puts("float is false\n"); if(j == 0.1) puts("double is true\n"); else puts("double is false\n"); return 0; } ------------- Output: ------------- float is false double is true
2 odpowiedzi
+ 5
float is false
double is true
That's because a floating point literal (value such as 0.1) by default is created with double type, as such, comparison `if(i == 0.1)` yields false because float type and double type differs in precision, and given enough decimal points, they are two different values.
I'm not sure why you want to see output
float is true
double is false
(As you wrote in the question) but you can achieve such output if you add an 'f' notation behind the 0.1 literal. Like this:
if (i == 0.1f) // float is true
if (j == 0.1f) // double is false
P.S. Please next time try to search first, as I remember this had been posted up some time ago : )
+ 5
Adding further to Ipang's answer, put these lines at the end of code and see what gets printed.
printf("Float: %.14f\n", i);
printf("Double: %.14f\n", j);
You'll notice that float loses it's precision. That's why i != 0.1
Hope it helps.