提交记录 #501
提交时间:2024-12-10 20:03:01
语言:c
状态:Accepted
编译情况:编译成功
固定测试点#1:
固定测试点#2:
固定测试点#3:
附加测试点暂不可用
5757.【中学】学生成绩排序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct {
char name[21]; // 学生姓名(长度不超过20个字符)
int score; // 学生成绩
} Student;
// 比较函数,用于排序
int compare_students(const void *a, const void *b) {
Student *studentA = (Student *)a;
Student *studentB = (Student *)b;
// 首先按成绩降序排序
if (studentA->score != studentB->score) {
return studentB->score - studentA->score;
}
// 如果成绩相同,保持输入顺序(稳定排序)
return 0;
}
int main() {
int n; // 学生数量
scanf("%d", &n); // 读取学生数量
// 动态分配学生数组
Student *students = (Student *)malloc(n * sizeof(Student));
if (students == NULL) {
printf("内存分配失败\n");
return 1;
}
// 读取学生数据
for (int i = 0; i < n; i++) {
char line[50];
scanf("%s", line); // 读取一行数据
// 解析姓名和成绩
char *comma = strchr(line, ',');
if (comma == NULL) {
printf("输入格式错误\n");
free(students);
return 1;
}
// 提取姓名
strncpy(students[i].name, line, comma - line);
students[i].name[comma - line] = '\0';
// 提取成绩
students[i].score = atoi(comma + 1);
}
// 使用 qsort 进行排序
qsort(students, n, sizeof(Student), compare_students);
// 输出排序结果
for (int i = 0; i < n; i++) {
printf("%s,%d\n", students[i].name, students[i].score);
}
// 释放内存
free(students);
return 0;
}