第 3 课

条件判断

一句话答案:if (条件) 只在条件为真时执行后面的块,else 执行另一种情况。条件就是一个求值为 true 或 false 的表达式。

比较运算产出布尔值

运算符含义例子
==等于a == 5
!=不等于a != 5
< > <= >=大小关系a <= 10

可以把比较结果直接打印出来,看它的 1/0 值 —— 快速确认 C++ 到底怎么想:

#include <iostream>
using namespace std;

int main() {
    int x = 7;
    cout << (x > 5) << endl;    // 1(真)
    cout << (x == 5) << endl;   // 0(假)
    cout << (x != 5) << endl;   // 1
    return 0;
}

三路选择

else if 按顺序测试,在第一个为真处停下:

#include <iostream>
using namespace std;

int main() {
    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                  cout << "F" << endl;
    return 0;
}

输入框里试试 95、85、75、60。顺序很重要:score >= 90 一旦为真,后面的测试就不再执行。

组合条件

&& 是「与」(两边都真),|| 是「或」(至少一边真),! 是「非」。闰年规则就是这个三路组合的经典:

#include <iostream>
using namespace std;

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

    bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    if (leap) cout << "leap year" << endl;
    else      cout << "not a leap year" << endl;
    return 0;
}

试试 1900(不是)、2000(是)、2024(是)。世纪规则为什么存在,见这道题的深度解析。

陷阱

配套练习

下面这几道题练的正是刚讲的内容: