带有单个else语句的多个if语句 [英] 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’;
答案密钥表示只有当等级<70时,此代码才能正常工作。我知道else语句与最后一个if语句相关联,但我仍然感到困惑。感谢您的帮助。
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.
推荐答案
您发布的代码段是4个独立的,无关的如果
语句,最后一个语句恰好有 else
条件。由于语句都是独立的,如果其中一个条件为真,那么也不会阻止其他if语句执行。
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.
在你的代码片段中,如果得分是例如95,然后将等级设置为'A',然后用'B'覆盖,然后用'C'覆盖,然后用'D'覆盖,最终将结果为'D'。但是,如果得分是< 70,结果从最终的遗留下来的结果如果
语句与正确的结果一致,因此它只留下等级
得分<时的正确结果70
。
In your snippet, if score was e.g. 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
.
正确的表格是:
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.
有关详细信息,请参阅关于 if-else
语句的官方教程。
For more information, see the official tutorial on if-else
statements.
这篇关于带有单个else语句的多个if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!