輸入 3 名學生的學號、姓名、3 門課成績,計算並輸出每門課的平均分。這是結構體數組、函數模塊化、指針傳參的綜合練習。
typedef struct {
int id; // 學號
char name[20]; // 姓名
float scores[3]; // 3 門課成績
float avg; // 個人平均分(可選)
} Student;
| 函數 | 功能 | 參數 |
|---|---|---|
void input(Student *stu, int n) | 鍵盤錄入 n 名學生信息 | 結構體指針、人數 |
void calcCourseAvg(Student *stu, int n, float *courseAvg) | 計算每門課平均分 | 結構體指針、人數、輸出數組 |
void printReport(Student *stu, int n, float *courseAvg) | 格式化輸出所有數據 | 結構體指針、人數、課程平均分 |
#include <stdio.h>
#define STU_NUM 3
#define COURSE_NUM 3
void input(Student *stu, int n) {
for (int i = 0; i < n; i++) {
printf("第 %d 位學生 (學號 姓名 三門成績): ", i+1);
scanf("%d %19s %f %f %f", &stu[i].id, stu[i].name,
&stu[i].scores[0], &stu[i].scores[1], &stu[i].scores[2]);
}
}
void calcCourseAvg(Student *stu, int n, float *courseAvg) {
for (int c = 0; c < COURSE_NUM; c++) {
float sum = 0;
for (int i = 0; i < n; i++) sum += stu[i].scores[c];
courseAvg[c] = sum / n;
}
}
void printReport(Student *stu, int n, float *courseAvg) {
printf("\n%-10s %-10s %s %s %s %-10s\n", "學號", "姓名", "課程1", "課程2", "課程3", "個人均分");
for (int i = 0; i < n; i++) {
float sum = 0;
printf("%-10d %-10s ", stu[i].id, stu[i].name);
for (int c = 0; c < COURSE_NUM; c++) {
printf("%-7.1f ", stu[i].scores[c]);
sum += stu[i].scores[c];
}
printf("%-7.1f\n", sum / COURSE_NUM);
}
printf("\n各課程平均分: ");
for (int c = 0; c < COURSE_NUM; c++) printf("課程%d: %.1f ", c+1, courseAvg[c]);
printf("\n");
}
int main() {
Student class[STU_NUM];
float courseAvg[COURSE_NUM];
input(class, STU_NUM);
calcCourseAvg(class, STU_NUM, courseAvg);
printReport(class, STU_NUM, courseAvg);
return 0;
}
malloc 分配 Student *class,運行時輸入人數。saveToFile/loadFromFile 實現數據存盤。qsort 配合比較函數。scanf 返回值,防止非法輸入導致程序崩潰。Student *stu 而非 Student stu[] 更直觀。%19s 限制寬度,防止覆蓋 name[20]。%.1f 或 %.2f,避免科學計數法。calloc 或手動置零,防止垃圾值參與計算。本例展示了 結構體封裝異構數據、函數單一職責、指針高效傳遞 的 C 語言工程化思想。掌握此模式,可快速構建通訊錄、庫存管理、考勤系統等實用小工具。