学生记录.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <stdio.h>
  2. #include <string.h>
  3. #define max 50
  4. #define length 20
  5. struct Student {
  6. int num;
  7. char name[length];
  8. int age;
  9. };
  10. int compareByName(const void *a, const void *b) {
  11. struct Student *studentA = (struct Student *)a;
  12. struct Student *studentB = (struct Student *)b;
  13. return strcmp(studentA->name, studentB->name);
  14. }
  15. int compareByAge(const void *a, const void *b) {
  16. struct Student *studentA = (struct Student *)a;
  17. struct Student *studentB = (struct Student *)b;
  18. if (studentA->age != studentB->age) {
  19. return studentA->age - studentB->age;
  20. } else {
  21. return strcmp(studentA->name, studentB->name);
  22. }
  23. }
  24. int main() {
  25. int n,i;
  26. scanf("%d", &n);
  27. struct Student students[max];
  28. for (i = 0; i < n; i++) {
  29. scanf("%d%s%d", &students[i].num, students[i].name, &students[i].age);
  30. }
  31. qsort(students, n, sizeof(struct Student), compareByName);
  32. for (i = 0; i < n; i++) {
  33. printf("%3d %6s %3d\n", students[i].num, students[i].name, students[i].age);
  34. }
  35. printf("\n");
  36. qsort(students, n, sizeof(struct Student), compareByAge);
  37. for (i = 0; i < n; i++) {
  38. printf("%3d %6s %3d\n", students[i].num, students[i].name, students[i].age);
  39. }
  40. return 0;
  41. }