每個學生是一個結構體:學號 id 和分數 score。用氣泡排序補全 sort_by_score(s, n),按分數從高到低排;分數一樣的保持原來的先後。show 用指標 p->id 顯示一個學生。程式會排好 5 個學生並一行一個顯示。
A02 95 A05 95 A04 88 A01 78 A03 62
#include <stdio.h>
struct Student {
char id[8];
int score;
};
void sort_by_score(struct Student s[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
// 在這裡寫:前一個分數比後一個低,就把兩個學生整個交換
}
}
}
void show(const struct Student *p) {
printf("%s %d\n", p->id, p->score);
}
int main(void) {
struct Student s[] = {{"A01", 78}, {"A02", 95}, {"A03", 62}, {"A04", 88}, {"A05", 95}};
sort_by_score(s, 5);
for (int i = 0; i < 5; i++) {
show(&s[i]);
}
return 0;
}
寫好了先點「執行」試試示例,沒問題再點「提交」。