简体   繁体   中英

Multiple if statements with single else statement

I'm reviewing for an exam and although we have an answer key, I don't understand the correct answer.

if (score >= 90)
    grade = 'A';
if (score >= 80)
    grade = 'B';
if (score >= 70)
    grade = 'C';
if (score >= 60) 
    grade = 'D';
else 
    grade = ‘F’;

The answer key says that "This code will work correctly only if grade < 70". I know the else statement is linked with the last if-statement, but I'm still confused. Thanks for the help in advance.

The snippet you've posted is 4 independent, unrelated if statements, and the last one happens to have an else condition. Since the statements are all separate, if one of the conditions is true, that doesn't prevent the other if statements from executing as well.

In your snippet, if score was eg 95, then grade would be set to 'A', then overwritten by 'B', then by 'C', then by 'D' and would ultimately end up as 'D'. However, if the score was < 70, the results left over from the final if statement would coincide with the correct results, hence it only leaves grade with the correct results when score < 70 .

The correct form would be:

if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else if (score >= 60) grade = 'D';
else grade = 'F';

If you try your code in a debugger with various inputs, and break on the first line, you can see exactly what is going on.

For more information, see the official tutorial on if-else statements .

That is correct. If the score is greater than 70, then the grade will be the last statement to run, so the last thing grade will be set to will always be 'D'. Thus, you need else if statements, or another technique, such as reversing all the if statements (ie putting if score>= 90 last).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM