题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
#include<stdio.h> #include<stdlib.h> typedef struct { char name[20]; int grade; } info; int cmp1(const void* p1, const void* p2) { // 低到高 return ((info*)p1)->grade - ((info*)p2)->grade; } int cmp2(const void* p1, const void* p2) { // 高到低 return ((info*)p2)->grade - ((info*)p1)->grade; } int main() { int n, mean; scanf("%d %d", &n, &mean); info stu[n]; for (int i = 0; i < n; i++) scanf("%s %d%*c", stu[i].name, &stu[i].grade); // qsort对结构体排序 if (mean == 0) qsort(stu, sizeof(stu) / sizeof(stu[0]), sizeof(stu[0]), cmp2); else qsort(stu, sizeof(stu) / sizeof(stu[0]), sizeof(stu[0]), cmp1); for (int i = 0; i < n; i++) printf("%s %d\n", stu[i].name, stu[i].grade); return 0; }