You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.5 KiB

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
struct Student {
char student_id[6];
int class_number;
float score1, score2, score3;
};
int compare_students(const void *a, const void *b) {
struct Student *student1 = (struct Student *)a;
struct Student *student2 = (struct Student *)b;
if (student1->class_number < student2->class_number) {
return -1;
} else if (student1->class_number > student2->class_number) {
return 1;
} else {
float total1 = student1->score1 + student1->score2 + student1->score3;
float total2 = student2->score1 + student2->score2 + student2->score3;
if (total1 < total2) {
return 1;
} else if (total1 > total2) {
return -1;
} else {
return 0;
}
}
}
int main() {
struct Student students[4];
int i;
strcpy(students[0].student_id, "10001");
students[0].class_number = 11;
students[0].score1 = 99.5;
students[0].score2 = 88.5;
students[0].score3 = 89.5;
strcpy(students[1].student_id, "10002");
students[1].class_number = 12;
students[1].score1 = 77.9;
students[1].score2 = 56.5;
students[1].score3 = 87.5;
strcpy(students[2].student_id, "10003");
students[2].class_number = 11;
students[2].score1 = 92.5;
students[2].score2 = 99.0;
students[2].score3 = 60.5;
int num_students = 3;
struct Student new_student;
printf("请输入新学生的信息 (学号 班级 成绩1 成绩2 成绩3): ");
scanf("%s %d %f %f %f", new_student.student_id, &new_student.class_number, &new_student.score1, &new_student.score2, &new_student.score3);
bool student_exists = false;
for (i = 0; i < num_students; i++) {
if (strcmp(new_student.student_id, students[i].student_id) == 0) {
student_exists = true;
break;
}
}
if (student_exists) {
printf("已存在学号的信息\n");
} else {
students[num_students] = new_student;
num_students++;
qsort(students, num_students, sizeof(struct Student), compare_students);
for (i = 0; i < num_students; i++) {
printf("%s %d %.1f %.1f %.1f", students[i].student_id, students[i].class_number, students[i].score1, students[i].score2, students[i].score3);
if (i == num_students - 1) {
printf(" inserted\n");
} else {
printf("\n");
}
}
}
return 0;
}