程式基礎概念

成績等級判定

運用 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>";
?>

給定一個成績數字,根據成績所在的區間,給定等級:
0 ~ 59 => E
60 ~ 69 => D
70 ~ 79 => C
80 ~ 89 => B
90 ~ 100 => A

您的成績是: 71 → 等級: C

邏輯判斷重點

  • 使用 && (AND) 運算子來結合兩個條件,確保數字落在正確的區間範圍內。
  • else if 提供了多重選擇,當上一個條件不成立時,會依序往下判斷。
  • 區間對照表:
    70 <= $score < 80  // 判定為 C 級
  • 最後的 else 處理異常狀況(如輸入負數或超過 100 ),增加程式的健壯性。