Why in first if else statement the output is false where in the second if else statement the output is true??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why in first if else statement the output is false where in the second if else statement the output is true???

This is the code https://code.sololearn.com/cpQgnA4utJZf/?ref=app

30th Nov 2018, 8:57 PM
onontohin jon
onontohin jon - avatar
4 Answers
+ 3
If you really want to geek out on understanding floating point numbers, there are a few really good videos on YouTube. One video that came to mind when I saw this question is from a channel I subscribe to called Computerphiles: https://youtu.be/PZRI1IfStY0
1st Dec 2018, 1:10 AM
David Carroll
David Carroll - avatar
+ 2
Because decimal floats are not exact. Since the numbers are converted from decimal to binary, the noninteger part usually has to be rounded. The rounding errors make it a hassle to compare floats for equality. Search the internet for 'float comparison'. The .5 is a specific case where the binary representation is exact. Well, it's just 1/2 in base 2. It would probably work with .25, .75, etc.
30th Nov 2018, 10:54 PM
Emerson Prado
Emerson Prado - avatar
+ 2
As an addition to what Emerson Prado is saying, if you change `float` to `double` it works. That's because when you do `i==.7`, you are comparing doubles, not floats. When you put `0.7` into a float you lose precision which then makes `i` sliiiightly less or more than a double `0.7`.
30th Nov 2018, 11:50 PM
Schindlabua
Schindlabua - avatar
+ 1
Cpp en que se basa ,para que sirve?podrian decirme
1st Dec 2018, 2:07 AM
Wander Anime
Wander Anime - avatar