From aeccbbc04e1f6f85bf2c87a46fa718699cd8df4c Mon Sep 17 00:00:00 2001 From: pui26hfw7 <125362001@qq.com> Date: Mon, 13 Nov 2023 22:16:05 +0800 Subject: [PATCH] ADD file via upload --- step4.c | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 step4.c diff --git a/step4.c b/step4.c new file mode 100644 index 0000000..45aa1c8 --- /dev/null +++ b/step4.c @@ -0,0 +1,93 @@ +#include +#include + +#define MAX_STUDENT_NUM 100 +#define MAX_NAME_LENGTH 20 + +typedef struct student_info { + int id; + int cls; + float scores[3]; + float total_score; + float avg_score; + int is_inserted; // 标记是否是插入的学生 +} student; + +void calc_score(student students[], int num) { + int i, j; + for (i = 0; i < num; i++) { + float total_score = 0; + for (j = 0; j < 3; j++) { + total_score += students[i].scores[j]; + } + students[i].total_score = total_score; + students[i].avg_score = total_score / 3; + } +} + +void insert_student(student students[], int* num, int id, int cls, float scores[3]) { + // 插入新学生信息 + students[*num].id = id; + students[*num].cls = cls; + students[*num].scores[0] = scores[0]; + students[*num].scores[1] = scores[1]; + students[*num].scores[2] = scores[2]; + students[*num].is_inserted = 1; // 设置标记为插入的学生 + + (*num)++; +} + +void sort_students(student students[], int num) { + // 使用冒泡排序,按cls升序,total_score降序 + for (int i = 0; i < num - 1; i++) { + for (int j = 0; j < num - i - 1; j++) { + if (students[j].cls > students[j + 1].cls || + (students[j].cls == students[j + 1].cls && students[j].total_score < students[j + 1].total_score)) { + // 交换元素 + student temp = students[j]; + students[j] = students[j + 1]; + students[j + 1] = temp; + } + } + } +} + +int main() { + student students[MAX_STUDENT_NUM] = { + {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 num = 3; // 已有学生数目 + int id, cls, i; + float scores[3]; + + printf("Please enter new student information:\n"); + scanf("%d %d %f %f %f", &id, &cls, &scores[0], &scores[1], &scores[2]); + + // 检查学号是否已存在 + for (i = 0; i < num; i++) { + if (students[i].id == id) { + printf("学号为%d的学生已存在\n", id); + return 0; + } + } + + insert_student(students, &num, id, cls, scores); + calc_score(students, num); + sort_students(students, num); + + for (i = 0; i < num; i++) { + printf("%d %d %.1f %.1f %.1f", students[i].id, students[i].cls, students[i].scores[0], students[i].scores[1], students[i].scores[2]); + + // 如果是插入的学生,则输出 "insert" + if (students[i].is_inserted == 1) { + printf(" insert"); + } + + printf("\n"); + } + + return 0; +}