+ 3

Q1: How this if else code works?

https://code.sololearn.com/cPTwldG5ILv2/?ref=app I found this code in challenge so I want to know how this works I tried to understand myself but I stuck.

3rd Nov 2019, 3:26 PM
Robin Singh
Robin Singh - avatar
8 odpowiedzi
+ 4
You should never compare floating point values for equality - due to known precision and rounding issues, the results are unpredictable. https://stackoverflow.com/questions/3988821/comparison-of-float-and-double-variables `0.7` is double, and `0.7f` is float.
3rd Nov 2019, 3:53 PM
o.gak
o.gak - avatar
+ 3
「HAPPY TO HELP」 Wait I don't get it, they are equal then it means that 0.7>a is false (how this returns true?) , so 3rd statement should be executed, but it's not... Also, if we change a to double, then 3rd statement is executed. edit: it seems that if we use float then "a" is less than 0.7 and if we use double then "a" becomes equal to 0.7 Definitely as o.gak said, don't compare float numbers for equality.
3rd Nov 2019, 4:04 PM
voja
voja - avatar
+ 3
Ivaturi Puja Ankitha I know how the if else statements works. I was only confuse between the double and float which the compiler automatically assumes a floating a number as a double if not mentioned float specially. btw thanks for the help everybody. float a=0.7; if(0.7f>a) print 1st else if(a>0.7f) print 2nd else print 3rd As both 1st and 2nd are false. So the 3rd will be printed.
3rd Nov 2019, 7:48 PM
Robin Singh
Robin Singh - avatar
+ 3
Robin Singh yeah! that is what i have mentioned in my answer :) thank you for the question.
3rd Nov 2019, 7:59 PM
Ivaturi Puja Ankitha
Ivaturi Puja Ankitha - avatar
+ 2
https://code.sololearn.com/cuB9bPCjn4bJ/?ref=app so, i have made a change in first two block conditions and made second one as true. through this, what i want to say is, if you won’t specify a decimal as float, it will be taking it defaultly as double which will be treated as bigger than the float value, even if they appear as same. coming to your question, in if else statements, if the if statement’s condition result true and executed, elseif and else blocks will be ignored.
3rd Nov 2019, 7:44 PM
Ivaturi Puja Ankitha
Ivaturi Puja Ankitha - avatar
+ 1
「HAPPY TO HELP」 You mean to say that (else if) is also true but I tried changing if condintion to the condition of (else if) but it returns false. a=0.7 (0.7>a) is true but (a>0.7) is false.
3rd Nov 2019, 3:56 PM
Robin Singh
Robin Singh - avatar
+ 1
In 'C' constants with decimal points are treated as double type. Since double have a precision (number of digits after point) of 16 digits and float have a precision of 6 digits. It is clear that a float type and a double type value can't be equal and double type is always greater than float type. In your code the variable a is of float type. So first condition comes to true.
5th Nov 2019, 11:52 AM
A2G4
0
هظi
5th Nov 2019, 12:19 PM
Yara Adam
Yara Adam - avatar