返回首页 C++ 模板

多层分支模板

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;
}

📖 要点说明

⚠️ 常见错误