+ 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

25th Aug 2019, 9:41 AM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
2 Antworten
+ 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 : )
25th Aug 2019, 10:27 AM
Ipang
+ 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.
25th Aug 2019, 10:47 AM
blACk sh4d0w
blACk sh4d0w - avatar