### Code always defaults to first "else if" in my if else statement.

Just to practice I wrote up a basic GPA calculator, but for some reason the code only prints out the first "else if" statement... but it always gets the grade right, so i know its working.. just not working right.

 else if (average > 89 || average < 100)

Need to be:
 else if (average > 89 && average < 100)

Your logic right now is if the grade is greater than 89 OR less than 100, which will always evaluate to true. So use && instead of || for your else ifs.
Thanks, and im sorry. Im brand new with this code language... Im switching up from C which i bearly knew in the first place. Thank you very much.
It's no problem and don't feel bad, that's actually a very common mistake people tend to make.
Comparing floating point values is a bad idea in most cases. Because of how computers store data even if you do 400.0 / 4 there is a (high) chance that the result will not be exactly 100, but rather something like 99.99999999987 (different from 100).
Last edited on
Well how do i fix something like that?
You can allow some degree of error with something like this
 12 const double ERROR = 0.000005; if(average >= 100 - ERROR && average <= 100 + ERROR)

But I'm not sure if it's the only viable option. When I have to deal with floats I just avoid equality comparisons.
On a side note, 0 can be exactly represented, so a comparison with 0 is "safer".
This is somewhat related... and I'm going to throw it out there because I see this problem a lot and it's a really, really bad habit.

You are duplicating code in the form of doubling your conditions. For example this bit here:

 1234 // ...Assuming the maximum value for 'average' is 100: if (average == 100){} else if (average > 89 || average < 100){}

else by definition will only execute if the previous if condition was false. Therefore the else here already ensures that average is less than 100. You do not (and should not) check for that again.

Something like this would be preferable:

 123 if(average >= 100) { } // <- avoid using == or != with floating points, as has been mentioned else if(average >= 90) { } // <- no need to see if average is less than 100... already know it is else if(average >= 80) { } // <- ditto

Aside from avoiding the confusion resulting with &&/|| mixups (which was your original problem), you remove code duplication which makes the code easier to maintain and less mistake-prone.
Topic archived. No new replies allowed.