简体   繁体   English

多个if语句和单个else语句

[英]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". 答案键说:“只有等级<70,此代码才能正常工作”。 I know the else statement is linked with the last if-statement, but I'm still confused. 我知道else语句与最后一个if语句链接,但是我仍然很困惑。 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. 您发布的代码段是4个独立的,不相关的if语句,最后一个恰好具有else条件。 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. 由于语句都是单独的,因此如果其中一个条件为真,则不会阻止其他if语句也执行。

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'. 在您的代码段中,如果得分为例如95,则等级将设置为“ A”,然后由“ B”,然后由“ C”,然后由“ D”覆盖,最终最终为“ 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 . 但是,如果得分<70,结果从最后遗留下来的if语句会用正确的结果一致,因此它只能离开grade与正确的结果时, 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 . 有关更多信息,请参见有关if-else语句的官方教程

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'. 如果分数大于70,则分数将是最后一个要执行的语句,因此将最后一个grade设置为始终为“ D”。 Thus, you need else if statements, or another technique, such as reversing all the if statements (ie putting if score>= 90 last). 因此,您需要其他if语句,或另一种技术,例如反转所有if语句(即,将if score>= 90放在最后)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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