diff --git a/4.c b/4.c new file mode 100644 index 0000000..2dca1e9 --- /dev/null +++ b/4.c @@ -0,0 +1,65 @@ +#include + +// 学生信息的结构体 +struct Student { + int id; + int class; + float score1; + float score2; + float score3; +}; + +// 插入新学生并保持数组有序的函数 +void insertStudent(struct Student students[], int* numStudents, struct Student newStudent) { + int i, j; + + // 检查学号是否已存在 + for (i = 0; i < *numStudents; i++) { + if (students[i].id == newStudent.id) { + printf("已存在学号的信息。\n"); + return; + } + } + + // 插入新学生信息并保持数组有序 + students[*numStudents] = newStudent; + (*numStudents)++; + for (i = 0; i < *numStudents - 1; i++) { + for (j = 0; j < *numStudents - i - 1; j++) { + if (students[j].class > students[j + 1].class || + (students[j].class == students[j + 1].class && students[j].score1 < students[j + 1].score1)) { + struct Student temp = students[j]; + students[j] = students[j + 1]; + students[j + 1] = temp; + } + } + } + + // 输出所有学生信息,包括插入标志 + for (i = 0; i < *numStudents; i++) { + printf("%d %d %.1f %.1f %.1f", students[i].id, students[i].class, students[i].score1, students[i].score2, students[i].score3); + if (i == *numStudents - 2) { + printf(" inserted"); + } + printf("\n"); + } +} + +int main() { + // 已有的三个学生信息 + struct Student students[3] = { + {10001, 11, 99.5, 88.5, 89.5}, + {10002, 12, 77.9, 56.5, 87.5}, + {10003, 11, 92.5, 99.0, 60.5} + }; + int numStudents = 3; + + // 输入新学生信息 + struct Student newStudent; + scanf("%d %d %f %f %f", &newStudent.id, &newStudent.class, &newStudent.score1, &newStudent.score2, &newStudent.score3); + + // 插入新学生信息并输出 + insertStudent(students, &numStudents, newStudent); + + return 0; +} \ No newline at end of file