結構體數組定義與成員訪問
struct stu {
char name[20];
long number;
float score[4]; // 0-2 三科,3 存平均
};
struct stu stud[20]; // 20 學生
// 訪問:stud[i].name, stud[i].score[j]
模組化設計七步走
- 輸入模組
input(arr, n):用 gets 讀姓名、學號、三科分,atol/atoi 轉數值。
- 平均計算
aver(arr, n):累加前三科存入 score[3]。
- 排序模組
order(arr, n):冒泡法按 score[3] 降序,整結構體交換(temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp;)。
- 表格輸出
output(arr, n):格式化列印姓名、學號、三科、平均,含表頭分隔線。
- 單科統計
out_row(arr, n):算四欄(三科+平均)平均,最後一行輸出。
- 主函數 串聯調用上述五模組。
完整程式碼骨架
#include
#include
struct stu { char name[20]; long number; float score[4]; };
void input(struct stu[], int);
void aver(struct stu[], int);
void order(struct stu[], int);
void output(struct stu[], int);
void out_row(struct stu[], int);
main() {
struct stu stud[4];
input(stud,4); aver(stud,4); order(stud,4);
output(stud,4); out_row(stud,4);
}
/* 各函數實現見原文 */
關鍵技術點
- 結構體數組作參數傳首址,形參寫
struct stu arr[] 不指定長度。
- 結構體整體可賦值交換,不可整體 I/O。
- 排序比較用
score[3],交換整個元素。