// max 函數中
if (students[i].computer > maxco) {
maxco = students[i+1].computer; // 錯誤:用 i+1 導致越界且邏輯錯
}
同樣問題存在於 min 函數,且未處理並列最高/最低分情況。
void max(Student students[]) {
maxch = maxma = maxen = maxco = students[0].chinese; // 初始化
for (int i = 1; i < 5; i++) {
if (students[i].chinese >= maxch) maxch = students[i].chinese;
if (students[i].math >= maxma) maxma = students[i].math;
if (students[i].english >= maxen) maxen = students[i].english;
if (students[i].computer>= maxco) maxco = students[i].computer; // 修正:用 i
}
}
void min(Student students[]) {
minch = minma = minen = minco = students[0].chinese;
for (int i = 1; i < 5; i++) {
if (students[i].chinese <= minch) minch = students[i].chinese;
if (students[i].math <= minma) minma = students[i].math;
if (students[i].english <= minen) minen = students[i].english;
if (students[i].computer<= minco) minco = students[i].computer;
}
}
| 問題 | 原代碼 | 修正 |
|---|---|---|
| Computer 索引越界 | students[i+1].computer | students[i].computer |
| 並列最高/最低分未更新 | > / < | >= / <=(可選,視需求) |
| 初始化冗余 | 分別賦值四次 | 鏈式賦值 maxch=maxma=...=students[0].chinese |
#define STU_NUM 5,便於擴展。sort 函數中 sum 數組未初始化,需在排序前計算總分:
for (i=0; i
scanf_s("%s", name) 需傳緩衝區大小:scanf_s("%s", name, 30)。