3.2 比較運算子

我們需要根據兩個值的大小關係來判斷條件。比較運算子就是做這件事的。

常用的比較運算子

運算子 意義 例子 結果
== 等於 5 == 5 true
!= 不等於 5 != 3 true
> 大於 5 > 3 true
< 小於 5 < 3 false
>= 大於或等於 5 >= 5 true
<= 小於或等於 5 <= 5 true

每個比較運算的結果是一個 booltruefalse)。

範例程式碼

#include <iostream>
using namespace std;

int main() {
    int score = 85;

    cout << boolalpha;  // 顯示 true/false 而不是 1/0
    cout << (score == 85) << endl;  // true
    cout << (score != 85) << endl;  // false
    cout << (score > 80) << endl;   // true
    cout << (score < 80) << endl;   // false
    cout << (score >= 85) << endl;  // true
    cout << (score <= 85) << endl;  // true

    return 0;
}

執行結果

true
false
true
false
true
true
圖 3-2:== 與 = 的差異

把中文/英文的說法翻成比較運算子

題目常常不會直接寫出 >=<,而是用日常語言描述條件。把這些說法對應到正確的比較運算子,是讀懂題目的基本功。下面整理常見的用法(假設門檻是 x):

中文說法 → 比較運算子

中文說法 比較運算子 含不含邊界 x
x 以上、滿 x、至少 x、不少於 x >= x x
x 以下、至多 x、最多 x、不超過 x <= x x
超過 x、大於 x、多於 x > x 不含 x
未滿 x、不足 x、小於 x、少於 x < x 不含 x
恰好 x、剛好 x、等於 x == x
不是 x、不等於 x != x
x 到 y 之間(含兩端) n >= x && n <= yn 是要判斷的值;&&=「且」,3.3 會教) 含 x、y

英文說法 → 比較運算子

英文說法 比較運算子
at least x、x or more、no less than x >= x
at most x、x or fewer、no more than x <= x
greater than x、more than x > x
less than x、fewer than x < x
exactly x、equal to x == x
not equal to x != x
between x and y (inclusive) n >= x && n <= y(見 3.3

動手試試看

寫一個程式,輸入一個整數 age,用比較運算子分別檢查:

  • 是否成年(>= 18)
  • 是否是小學生(< 13)
  • 是否恰好 18 歲(== 18)

輸出三個結果。