運用 if...else 多重分支邏輯,實作自動化成績等級分類系統。
// 【程式碼練習】
// 依成績區間給定等級(E / D / C / B / A),範圍外視為輸入錯誤。
$score = 71;
$level = '';
if ($score >= 0 && $score < 60) {
$level = 'E';
} else if ($score >= 60 && $score < 70) {
$level = 'D';
} else if ($score >= 70 && $score < 80) {
$level = 'C';
} else if ($score >= 80 && $score < 90) {
$level = 'B';
} else if ($score >= 90 && $score <= 100) {
$level = 'A';
} else {
$level = '成績輸入錯誤';
}
echo "您的成績是: <strong>" . $score . "</strong> → 等級: <strong>" . $level . "</strong>";
【學習重點】
&& 結合上下界,讓分數落在正確範圍才指定等級。else if 由上而下檢查,上一個不成立才繼續。else 承接負數、超過 100 等不合理輸入。70 <= $score < 80 對應 C 級(實作時仍以兩段比較式寫成條件)。
$score >= 0)以利閱讀與除錯。