题目

定义学生结构体 Student(包含姓名与成绩),读入 n 名学生的数据,调用 qsort 按成绩从高到低降序排序,并依次输出学生姓名与成绩。

输入格式:第一行输入学生人数 n;随后 n 行每行输入学生姓名(无空格)和整数成绩。

输出格式:按成绩降序分行输出排序后的学生姓名与成绩。

数据范围与约定:1 ≤ n ≤ 100,成绩为整数。

思路与算法

1. 结构体数组模型
声明 struct Student list[100]; 管理批量记录。

2. qsort 结构体比较函数
比较函数参数转换为结构体指针 const struct Student *s1 = (const struct Student *)a;。降序排序返回 s2->score - s1->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);
    }

    // 结构体整体交换:C 语言支持直接给同类型结构体赋值,内部字段自动整体复制
    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