需求:輸入 n 位學生的學號、姓名、3 門成績,按平均分從高到低輸出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
long id;
char name[32];
float scores[3];
float avg;
} Student;
int cmp_desc(const void *a, const void *b) {
const Student *s1 = (const Student *)a;
const Student *s2 = (const Student *)b;
return (s2->avg > s1->avg) - (s2->avg < s1->avg); // 降序
}
int main() {
int n;
printf("請輸入學生人數 n: ");
if (scanf("%d", &n) != 1 || n <= 0) return 1;
Student *stu = malloc(n * sizeof(Student));
if (!stu) return 1;
for (int i = 0; i < n; i++) {
printf("第 %d 位: 學號 姓名 成績1 成績2 成績3\n", i + 1);
scanf("%ld %31s %f %f %f", &stu[i].id, stu[i].name,
&stu[i].scores[0], &stu[i].scores[1], &stu[i].scores[2]);
stu[i].avg = (stu[i].scores[0] + stu[i].scores[1] + stu[i].scores[2]) / 3.0f;
}
qsort(stu, n, sizeof(Student), cmp_desc);
printf("\n%-10s %-10s %6s %6s %6s %6s\n", "學號", "姓名", "成績1", "成績2", "成績3", "平均分");
for (int i = 0; i < n; i++) {
printf("%-10ld %-10s %6.1f %6.1f %6.1f %6.2f\n",
stu[i].id, stu[i].name,
stu[i].scores[0], stu[i].scores[1], stu[i].scores[2], stu[i].avg);
}
free(stu);
return 0;
}
掌握「結構體 + qsort + 動態記憶體」是 C 語言處理結構化資料排序的標準範式。