题目
结构体数组:按成绩排序输出学生姓名
思路
本题读入多名学生的姓名和成绩,按成绩从高到低输出姓名。
用结构体数组存数据,写比较函数按 score 降序,调用 qsort 排序后依次打印 name。
解题分析
结构体数组排序交换整 struct 或交换下标。按成绩降序用冒泡/选择均可,比较字段 score。
完整程序
#include <stdio.h>
#include <string.h>
struct Student {
char name[32];
int score;
};
int main(void)
{
struct Student st[3];
for (int i = 0; i < 3; i++) {
scanf("%31s %d", st[i].name, &st[i].score);
}
for (int i = 0; i < 2; i++) {
for (int j = i + 1; j < 3; j++) {
if (st[j].score > st[i].score) {
struct Student t = st[i];
st[i] = st[j];
st[j] = t;
}
}
}
for (int i = 0; i < 3; i++) {
printf("%s\n", st[i].name);
}
return 0;
}
运行示例
输入:
Amy 85
Bob 92
Cal 78输出:
Bob
Amy
Cal