第 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(是)。世纪规则为什么存在,见这道题的深度解析。
陷阱
=和==。if (x = 5)是赋值,永远为真 —— 无声的 bug。写成if (5 == x)可以让编译器帮你抓。- 少了花括号。
if (a) if (b) x(); else y();里的else会绑到最近的if。永远加花括号。 - 连写比较。
0 < x < 10能编译但是错的(它等价于(0 < x) < 10)。写0 < x && x < 10。