多层分支模板
if-else 嵌套与 else-if 阶梯——处理多条件多层次的判断
多层分支
嵌套if
else-if
GESP2
#include <bits/stdc++.h>
using namespace std;
int main() {
// else-if 阶梯
int score;
cin >> score;
if (score >= 90) cout << "A" << endl;
else if (score >= 80) cout << "B" << endl;
else if (score >= 70) cout << "C" << endl;
else if (score >= 60) cout << "D" << endl;
else cout << "F" << endl;
// 嵌套 if
int year;
cin >> year;
if (year >= 0) {
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) cout << "闰年" << endl;
else cout << "平年" << endl;
} else {
cout << "闰年" << endl;
}
} else {
cout << "平年" << endl;
}
}
// 闰年简化写法
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
cout << "闰年" << endl;
return 0;
}
📖 要点说明
- else-if 阶梯按从高到低排列,只走第一个满足的分支
- 嵌套过深时可简化为逻辑表达式
- 闰年公式:
能4整除且不能100整除,或能400整除
⚠️ 常见错误
- else-if 顺序错:先判断
>=60再判断>=90,后者永远不执行 - 嵌套 if 的 else 匹配问题:else 与最近的 if 配对
- 闰年判断忘考虑 400 的特殊情况