+ 3

please explain

float f=0.1; if(f==0.1) cout<<"true"; else cout<<"false"; the answer is false why?

20th Mar 2019, 7:51 PM
Vishesh Saxena
Vishesh Saxena - avatar
8 Answers
+ 4
Welcome 😊.. Vishesh Saxena
20th Mar 2019, 8:06 PM
Scooby
Scooby - avatar
+ 3
You need to replace float with double. But it is still weird, because I would expect that float will work too.
20th Mar 2019, 7:59 PM
Jan Ơtěch
Jan Ơtěch - avatar
+ 2
0.//exploration float f=0.1 >means f has 0.1 float value if(f==0.1) >if checking that f value is equal (==) to 0.1, its not because f= 0.1, here 0.1 is not declared as float, its directly declared as double literal so it is not equal cout="false"
20th Mar 2019, 8:05 PM
Sudarshan Rai
Sudarshan Rai - avatar
+ 1
0.1 is of type double. Try this: if (f == (float) 0.1)
20th Mar 2019, 8:00 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
Jan Ơtěch Why? 0.1 will obviously be better approximated with better precision (and as such be different).
20th Mar 2019, 8:01 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
Scooby thanks for the link .
20th Mar 2019, 8:05 PM
Vishesh Saxena
Vishesh Saxena - avatar
0
Vlad Serbu thanks that too fit in the answer
20th Mar 2019, 8:06 PM
Vishesh Saxena
Vishesh Saxena - avatar