Serie: C++
cpp
228 líneas
· Actualizado 2026-04-03
if_else.cpp
C++/Part1_基礎入門/Ch03_控制流程/if_else.cpp
// ============================================================
// Ch03 - 條件判斷(if / else if / else)
// 編譯:g++ -std=c++17 -Wall -o if_else if_else.cpp
// 執行:./if_else
// ============================================================
#include <iostream>
#include <string>
int main() {
// ══════════════════════════════════════════
// 1. 基本 if / else
// ══════════════════════════════════════════
std::cout << "=== 基本 if / else ===" << std::endl;
int temperature = 35;
if (temperature >= 30) {
std::cout << "氣溫 " << temperature << "°C → 很熱!記得多喝水" << std::endl;
} else {
std::cout << "氣溫 " << temperature << "°C → 還可以" << std::endl;
}
// ══════════════════════════════════════════
// 2. if / else if / else 多條件判斷
// ══════════════════════════════════════════
std::cout << "\n=== 多條件判斷 ===" << std::endl;
int temp = 15;
std::cout << "氣溫 " << temp << "°C → ";
if (temp >= 35) {
std::cout << "酷熱,注意中暑" << std::endl;
} else if (temp >= 28) {
std::cout << "炎熱" << std::endl;
} else if (temp >= 20) {
std::cout << "舒適" << std::endl;
} else if (temp >= 10) {
std::cout << "涼爽,建議加件外套" << std::endl;
} else if (temp >= 0) {
std::cout << "寒冷,注意保暖" << std::endl;
} else {
std::cout << "零下!極度寒冷" << std::endl;
}
// ══════════════════════════════════════════
// 3. 成績等第計算器
// ══════════════════════════════════════════
std::cout << "\n=== 成績等第計算器 ===" << std::endl;
int scores[] = {95, 82, 73, 65, 48};
for (int score : scores) {
std::string grade;
std::string comment;
if (score >= 90) {
grade = "A";
comment = "優秀!繼續保持";
} else if (score >= 80) {
grade = "B";
comment = "良好,還有進步空間";
} else if (score >= 70) {
grade = "C";
comment = "普通,需要更努力";
} else if (score >= 60) {
grade = "D";
comment = "勉強及格,要加油了";
} else {
grade = "F";
comment = "不及格,需要補考";
}
std::cout << "分數:" << score
<< " → 等第:" << grade
<< "(" << comment << ")" << std::endl;
}
// ══════════════════════════════════════════
// 4. 邏輯運算子搭配 if
// ══════════════════════════════════════════
std::cout << "\n=== 邏輯運算子與條件 ===" << std::endl;
int age = 25;
bool hasTicket = true;
// AND(&&):兩者都要滿足
if (age >= 18 && hasTicket) {
std::cout << "年齡 " << age << ",有票 → 可以入場" << std::endl;
}
// OR(||):至少一個滿足
int day = 6; // 星期六
if (day == 6 || day == 7) {
std::cout << "今天是週末,放假!" << std::endl;
}
// NOT(!):反轉條件
bool isRaining = false;
if (!isRaining) {
std::cout << "沒有下雨,適合出門" << std::endl;
}
// 複合條件
int studentAge = 20;
double gpa = 3.8;
bool isInternational = false;
if ((studentAge >= 18 && studentAge <= 25) && (gpa >= 3.5 || isInternational)) {
std::cout << "符合獎學金申請資格" << std::endl;
}
// ══════════════════════════════════════════
// 5. 巢狀 if
// ══════════════════════════════════════════
std::cout << "\n=== 巢狀 if ===" << std::endl;
int userAge = 20;
bool hasLicense = true;
bool hasCar = false;
if (userAge >= 18) {
std::cout << "已成年" << std::endl;
if (hasLicense) {
std::cout << " 有駕照" << std::endl;
if (hasCar) {
std::cout << " 有車 → 可以自己開車" << std::endl;
} else {
std::cout << " 沒車 → 可以租車" << std::endl;
}
} else {
std::cout << " 沒駕照 → 請先考駕照" << std::endl;
}
} else {
std::cout << "未成年,不能開車" << std::endl;
}
// ══════════════════════════════════════════
// 6. if 的單行簡寫(不建議複雜邏輯使用)
// ══════════════════════════════════════════
std::cout << "\n=== 單行 if ===" << std::endl;
int value = 42;
// 如果只有一個敘述,可以省略大括號(但不建議)
if (value > 0)
std::cout << value << " 是正數" << std::endl;
// 建議永遠加大括號,避免後續修改時出錯
if (value > 0) {
std::cout << value << " 是正數(加大括號版)" << std::endl;
}
// ══════════════════════════════════════════
// 7. 常見錯誤示範
// ══════════════════════════════════════════
std::cout << "\n=== 常見錯誤提醒 ===" << std::endl;
int num = 5;
// 錯誤:用 = 而非 ==
// if (num = 10) { // 這是賦值,會把 num 改成 10,且條件永遠為 true
// std::cout << "這永遠會執行" << std::endl;
// }
// 正確:用 ==
if (num == 10) {
std::cout << "num 是 10" << std::endl;
} else {
std::cout << "num 不是 10(num = " << num << ")" << std::endl;
}
// 防禦技巧:把常數放左邊(Yoda Condition)
// if (10 == num) { ... } // 如果誤寫成 = 會編譯錯誤
// ══════════════════════════════════════════
// 8. 實用範例:BMI 計算
// ══════════════════════════════════════════
std::cout << "\n=== BMI 計算範例 ===" << std::endl;
double weight = 70.0; // 公斤
double height = 1.75; // 公尺
double bmi = weight / (height * height);
std::cout << "體重:" << weight << " kg" << std::endl;
std::cout << "身高:" << height << " m" << std::endl;
std::cout << "BMI:" << bmi << std::endl;
std::cout << "判定:";
if (bmi < 18.5) {
std::cout << "體重過輕" << std::endl;
} else if (bmi < 24.0) {
std::cout << "正常範圍" << std::endl;
} else if (bmi < 27.0) {
std::cout << "過重" << std::endl;
} else if (bmi < 30.0) {
std::cout << "輕度肥胖" << std::endl;
} else if (bmi < 35.0) {
std::cout << "中度肥胖" << std::endl;
} else {
std::cout << "重度肥胖" << std::endl;
}
// ══════════════════════════════════════════
// 9. 三元運算子作為簡單 if/else 的替代
// ══════════════════════════════════════════
std::cout << "\n=== 三元運算子 ===" << std::endl;
int a = 10, b = 20;
// if/else 寫法
int maxVal;
if (a > b) {
maxVal = a;
} else {
maxVal = b;
}
std::cout << "較大值(if/else):" << maxVal << std::endl;
// 三元運算子寫法(更簡潔)
int maxVal2 = (a > b) ? a : b;
std::cout << "較大值(三元):" << maxVal2 << std::endl;
// 直接用在輸出中
int number = -3;
std::cout << number << " 是" << ((number >= 0) ? "非負數" : "負數") << std::endl;
return 0;
}
Artículos relacionados
C++
c
Actualizado 2026-07-21
deviceAlpha.h
deviceAlpha.h — c source code from the C++ learning materials (C++/Mavis_Homework/FinalProject/deviceAlpha.h).
Leer artículo →
C++
c
Actualizado 2026-07-21
finalproject.c
finalproject.c — c source code from the C++ learning materials (C++/Mavis_Homework/FinalProject/finalproject.c).
Leer artículo →
C++
cpp
Actualizado 2026-07-21
finalproject.cpp
finalproject.cpp — cpp source code from the C++ learning materials (C++/Mavis_Homework/FinalProject/finalproject.cpp).
Leer artículo →
C++
c
Actualizado 2026-07-21
deviceAlpha.h
deviceAlpha.h — c source code from the C++ learning materials (C++/Mavis_Homework/Lab8/deviceAlpha.h).
Leer artículo →
C++
c
Actualizado 2026-07-21
lab8.c
lab8.c — c source code from the C++ learning materials (C++/Mavis_Homework/Lab8/lab8.c).
Leer artículo →
C++
cpp
Actualizado 2026-07-21
lab8.cpp
lab8.cpp — cpp source code from the C++ learning materials (C++/Mavis_Homework/Lab8/lab8.cpp).
Leer artículo →