返回首页 C++ 模板

分支语句模板

if-else、switch-case——让程序根据条件选择不同路径

if-else switch-case 分支 GESP1
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;

    // if-else
    if (n > 0) cout << "正数" << endl;
    else if (n < 0) cout << "负数" << endl;
    else cout << "零" << endl;

    // 多条件
    int score;
    cin >> score;
    if (score >= 90) cout << "优秀" << endl;
    else if (score >= 80) cout << "良好" << endl;
    else if (score >= 60) cout << "及格" << endl;
    else cout << "不及格" << endl;

    // switch-case
    int day;
    cin >> day;
    switch (day) {
        case 1: cout << "周一" << endl; break;
        case 2: cout << "周二" << endl; break;
        default: cout << "其他" << endl; break;
    }

    // 三目运算符
    int a = 5, b = 3;
    cout << ((a > b) ? a : b) << endl;  // 5

    return 0;
}

📖 要点说明

⚠️ 常见错误