有一说一,这个c语言的qsort真的很难用,这里cmp的写法需要大家注意下,否则很难过关
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> typedef struct student{ int num, age; char name[15]; } student; int cmp(const void *s1, const void *s2) { student* a = (student*) s1; student* b = (student*) s2; if (a->age == b->age && a->num == b->num) return strcmp(a->name, b->name); else if (a->age == b->age) return a->num - b->num; return a->age - b->age; } int main() { int n; student stu[35]; while (scanf("%d", &n) != EOF) { for (int i = 0; i < n; i++) { int num, age; char name[15]; scanf("%d %s %d", &num, name, &age); stu[i].num = num; strcpy(stu[i].name, name); stu[i].age = age; } qsort(stu, n, sizeof(student), cmp); for (int i = 0; i < 3; i++) { printf("%d %s %d\n", stu[i].num, stu[i].name, stu[i].age); } } return 0; }