diff --git a/作业2.4.c b/作业2.4.c new file mode 100644 index 0000000..84b37fc --- /dev/null +++ b/作业2.4.c @@ -0,0 +1,62 @@ +#include +#include // °üº¬ÁË qsort º¯ÊýËùÐèµÄÍ·Îļþ + +// ѧÉúÐÅÏ¢µÄ½á¹¹Ìå +struct Student { + int student_id; + int class_id; + float score1; + float score2; + float score3; +}; + +// ±È½Ïº¯Êý£¬ÓÃÓÚÅÅÐò +int compareStudents(const void *a, const void *b) { + struct Student *student1 = (struct Student *)a; + struct Student *student2 = (struct Student *)b; + + if (student1->class_id != student2->class_id) { + return student1->class_id - student2->class_id; + } else { + float total_score1 = student1->score1 + student1->score2 + student1->score3; + float total_score2 = student2->score1 + student2->score2 + student2->score3; + return total_score2 - total_score1; + } +} + +int main() { + struct Student students[100]; + int num_students = 3; // ³õʼÓÐ3¸öѧÉúÐÅÏ¢ + + // ³õʼ»¯ÒÑÓÐѧÉúÐÅÏ¢ + students[0] = (struct Student){10001, 11, 99.5, 88.5, 89.5}; + students[1] = (struct Student){10002, 12, 77.9, 56.5, 87.5}; + students[2] = (struct Student){10003, 11, 92.5, 99.0, 60.5}; + + // ¶ÔÒÑÓÐѧÉúÐÅÏ¢½øÐÐÅÅÐò + qsort(students, num_students, sizeof(struct Student), compareStudents); + + // ÊäÈëÐÂѧÉúÐÅÏ¢ + struct Student new_student; + printf("ÊäÈëÐÂѧÉúÐÅÏ¢£¨Ñ§ºÅ °à¼¶ ³É¼¨1 ³É¼¨2 ³É¼¨3£©£º"); + scanf("%d %d %f %f %f", &new_student.student_id, &new_student.class_id, &new_student.score1, &new_student.score2, &new_student.score3); + + // ²åÈëÐÂѧÉúÐÅÏ¢ + students[num_students] = new_student; + num_students++; + + // ¶ÔÐÂÊý¾Ý½øÐÐÅÅÐò + qsort(students, num_students, sizeof(struct Student), compareStudents); + + for (int i = 0; i < num_students; i++) { + printf("%d %d %.1f %.1f %.1f", students[i].student_id, students[i].class_id, students[i].score1, students[i].score2, students[i].score3); + if (i == num_students - 2) { + printf(" inserted\n"); + } else { + printf("\n"); + } + } + + return 0; +} +