運用 if...else 多重分支邏輯,實作自動化成績等級分類系統。
<?php
$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>";
?>
邏輯判斷重點
&& (AND) 運算子來結合兩個條件,確保數字落在正確的區間範圍內。else if 提供了多重選擇,當上一個條件不成立時,會依序往下判斷。70 <= $score < 80 // 判定為 C 級
else 處理異常狀況(如輸入負數或超過 100 ),增加程式的健壯性。