C程序if else if语句第二、第三分支执行异常如何解决
问题根因
你在多分支判断中错误使用了C语言的逗号运算符,该运算符的运算规则为:按从左到右顺序计算所有子表达式后,仅返回最右侧子表达式的结果,左侧所有子表达式的结果会被直接丢弃。
所以你写的4个分支判断,实际生效的条件分别为:
- 第一个if:仅判断
maths_score>=33,忽略sci_score的取值 - 第二个else if:仅判断
maths_score<33,忽略sci_score的取值
上述两个条件已经覆盖了所有可能的输入场景,因此第三、第四个分支永远不会被触发。
修复方案
将所有分支判断中的逗号,替换为逻辑与运算符&&即可。逻辑与运算符要求左右两侧条件同时为真时,整个表达式才为真,符合你原本想要同时判断两个科目分数的逻辑。
另外你代码中两个输入提示的printf语句包含多余的参数,在没有占位符的场景下不需要传入sci_score和maths_score,可直接删除冗余参数。最后一个分支可以直接简化为else,因为前面三个条件已经覆盖了其他所有情况,不需要再重复判断。
修复后完整代码
#include <stdio.h> int main() { int sci_score, maths_score; printf("enter your sci score:"); scanf("%d", &sci_score); printf("enter your maths score:"); scanf("%d", &maths_score); if(sci_score>=33 && maths_score>=33) { printf("you are awarded with ruppees 45"); } else if(sci_score>=33 && maths_score<33) { printf("you are awarded with ruppees 15. work hard in maths"); } else if(sci_score<33 && maths_score>=33) { printf("you are awarded with ruppees 15. work hard in sci"); } else { printf("work hard in sci and maths"); } return 0; }
内容的提问来源于stack exchange,提问作者Divyanshu Kumar
相关产品推荐
相关产品推荐

