S SmartDocs
Serie: C++ cpp 182 líneas · Actualizado 2026-04-03

operators.cpp

C++/Part1_基礎入門/Ch02_變數與資料型別/operators.cpp

// ============================================================
// Ch02 - 運算子示範
// 編譯:g++ -std=c++17 -Wall -o operators operators.cpp
// 執行:./operators
// ============================================================

#include <iostream>

int main() {
    // ══════════════════════════════════════════
    // 1. 算術運算子(Arithmetic Operators)
    // ══════════════════════════════════════════
    std::cout << "=== 算術運算子 ===" << std::endl;

    int a = 17, b = 5;
    std::cout << a << " + " << b << " = " << (a + b) << std::endl;   // 22
    std::cout << a << " - " << b << " = " << (a - b) << std::endl;   // 12
    std::cout << a << " * " << b << " = " << (a * b) << std::endl;   // 85
    std::cout << a << " / " << b << " = " << (a / b) << std::endl;   // 3(整數除法,截斷小數)
    std::cout << a << " % " << b << " = " << (a % b) << std::endl;   // 2(取餘數)

    // 整數除法 vs 浮點數除法
    std::cout << "\n--- 整數除法 vs 浮點數除法 ---" << std::endl;
    std::cout << "整數:17 / 5 = " << (17 / 5) << std::endl;         // 3
    std::cout << "浮點:17.0 / 5 = " << (17.0 / 5) << std::endl;     // 3.4
    std::cout << "轉型:static_cast<double>(17) / 5 = "
              << (static_cast<double>(17) / 5) << std::endl;          // 3.4

    // 負數取餘
    std::cout << "\n--- 負數取餘 ---" << std::endl;
    std::cout << "-17 % 5 = " << (-17 % 5) << std::endl;   // -2(結果的正負號跟隨被除數)
    std::cout << "17 % -5 = " << (17 % -5) << std::endl;   // 2

    // ══════════════════════════════════════════
    // 2. 比較運算子(Comparison Operators)
    // ══════════════════════════════════════════
    std::cout << "\n=== 比較運算子 ===" << std::endl;

    int x = 10, y = 20;
    std::cout << std::boolalpha;  // 讓 bool 顯示為 true/false

    std::cout << x << " == " << y << " → " << (x == y) << std::endl;   // false
    std::cout << x << " != " << y << " → " << (x != y) << std::endl;   // true
    std::cout << x << " <  " << y << " → " << (x < y) << std::endl;    // true
    std::cout << x << " >  " << y << " → " << (x > y) << std::endl;    // false
    std::cout << x << " <= " << y << " → " << (x <= y) << std::endl;   // true
    std::cout << x << " >= " << y << " → " << (x >= y) << std::endl;   // false

    // 比較的結果是 bool 值(true = 1, false = 0)
    bool result = (x < y);
    std::cout << "\n比較結果存入 bool:(10 < 20) = " << result << std::endl;

    // ══════════════════════════════════════════
    // 3. 邏輯運算子(Logical Operators)
    // ══════════════════════════════════════════
    std::cout << "\n=== 邏輯運算子 ===" << std::endl;

    bool p = true, q = false;

    std::cout << "true  && true  = " << (true && true) << std::endl;    // true
    std::cout << "true  && false = " << (p && q) << std::endl;          // false
    std::cout << "false && false = " << (false && false) << std::endl;  // false

    std::cout << "true  || true  = " << (true || true) << std::endl;    // true
    std::cout << "true  || false = " << (p || q) << std::endl;          // true
    std::cout << "false || false = " << (false || false) << std::endl;  // false

    std::cout << "!true  = " << (!p) << std::endl;    // false
    std::cout << "!false = " << (!q) << std::endl;     // true

    // 實際應用:範圍判斷
    int age = 25;
    bool isAdult = (age >= 18) && (age < 65);
    std::cout << "\n年齡 " << age << " 是否為成年工作者:" << isAdult << std::endl;

    // 短路求值(Short-circuit evaluation)
    // && 左邊為 false 時,右邊不會被執行
    // || 左邊為 true 時,右邊不會被執行
    std::cout << "\n--- 短路求值 ---" << std::endl;
    int num = 0;
    // 因為 num == 0 為 true(||),右邊的 100/num 不會執行(避免除以零)
    if (num == 0 || 100 / num > 5) {
        std::cout << "短路求值避免了除以零的錯誤" << std::endl;
    }

    // ══════════════════════════════════════════
    // 4. 指定運算子(Assignment Operators)
    // ══════════════════════════════════════════
    std::cout << "\n=== 指定運算子 ===" << std::endl;

    int val = 100;
    std::cout << "初始值:val = " << val << std::endl;

    val += 10;  // val = val + 10
    std::cout << "val += 10 → " << val << std::endl;    // 110

    val -= 30;  // val = val - 30
    std::cout << "val -= 30 → " << val << std::endl;    // 80

    val *= 2;   // val = val * 2
    std::cout << "val *= 2  → " << val << std::endl;    // 160

    val /= 4;   // val = val / 4
    std::cout << "val /= 4  → " << val << std::endl;    // 40

    val %= 7;   // val = val % 7
    std::cout << "val %= 7  → " << val << std::endl;    // 5

    // ══════════════════════════════════════════
    // 5. 遞增 / 遞減運算子(Increment / Decrement)
    // ══════════════════════════════════════════
    std::cout << "\n=== 遞增 / 遞減運算子 ===" << std::endl;

    int counter = 10;

    // 前置遞增(prefix):先加 1,再取值
    std::cout << "初始值:" << counter << std::endl;
    std::cout << "++counter = " << (++counter) << std::endl;  // 11(先加再用)
    std::cout << "現在 counter = " << counter << std::endl;   // 11

    // 後置遞增(postfix):先取值,再加 1
    std::cout << "counter++ = " << (counter++) << std::endl;  // 11(先用再加)
    std::cout << "現在 counter = " << counter << std::endl;   // 12

    // 前置遞減
    std::cout << "--counter = " << (--counter) << std::endl;  // 11
    std::cout << "現在 counter = " << counter << std::endl;   // 11

    // 後置遞減
    std::cout << "counter-- = " << (counter--) << std::endl;  // 11(先用再減)
    std::cout << "現在 counter = " << counter << std::endl;   // 10

    // 注意:盡量避免在同一運算式中對同一變數多次使用 ++ 或 --
    // 例如 i = i++ + ++i; 是未定義行為

    // ══════════════════════════════════════════
    // 6. 三元運算子(Ternary Operator)
    // ══════════════════════════════════════════
    std::cout << "\n=== 三元運算子 ===" << std::endl;

    // 語法:條件 ? 真值 : 假值
    int score = 75;
    std::string grade = (score >= 60) ? "及格" : "不及格";
    std::cout << "分數 " << score << ":" << grade << std::endl;

    // 求兩數中的較大值
    int m = 42, n = 58;
    int maxVal = (m > n) ? m : n;
    std::cout << m << " 和 " << n << " 中較大的是:" << maxVal << std::endl;

    // 巢狀三元運算子(可讀性較差,不建議過度使用)
    int testScore = 85;
    std::string level = (testScore >= 90) ? "優" :
                        (testScore >= 80) ? "良" :
                        (testScore >= 70) ? "可" :
                        (testScore >= 60) ? "差" : "不及格";
    std::cout << "成績 " << testScore << " → 等第:" << level << std::endl;

    // ══════════════════════════════════════════
    // 7. 運算子優先順序示範
    // ══════════════════════════════════════════
    std::cout << "\n=== 運算子優先順序 ===" << std::endl;

    // 乘除優先於加減
    std::cout << "2 + 3 * 4 = " << (2 + 3 * 4) << std::endl;      // 14(非 20)
    std::cout << "(2 + 3) * 4 = " << ((2 + 3) * 4) << std::endl;  // 20

    // 比較運算子優先於邏輯運算子
    int v = 15;
    bool check = v > 10 && v < 20;  // 等同於 (v > 10) && (v < 20)
    std::cout << "15 > 10 && 15 < 20 = " << check << std::endl;   // true

    // && 優先於 ||
    bool r1 = true || (false && false);  // true || (false && false) = true || false = true
    bool r2 = (true || false) && false; // true && false = false
    std::cout << "true || false && false = " << r1 << std::endl;    // true
    std::cout << "(true || false) && false = " << r2 << std::endl;  // false

    std::cout << "\n建議:不確定優先順序時,善用括號讓程式碼更清晰!" << std::endl;

    return 0;
}

Artículos relacionados