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.

85 lines
3.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <stdio.h>
#include <stdlib.h> // 包含了 qsort 函数所需的头文件
#include <string.h> // 包含了字符串处理函数所需的头文件
// 学生信息的结构体
struct Student {
int student_id;
int class_id;
char name[50];
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, "Zhang", 99.5, 88.5, 89.5};
students[1] = (struct Student){10002, 12, "Yang", 77.9, 56.5, 87.5};
students[2] = (struct Student){10003, 11, "Liang", 92.5, 99.0, 60.5};
// 对已有学生信息进行排序
qsort(students, num_students, sizeof(struct Student), compareStudents);
// 输入待修改学生的信息
struct Student modified_student;
printf("输入待修改学生的信息(学号 班级 姓名 成绩1 成绩2 成绩3");
scanf("%d %d %s %f %f %f", &modified_student.student_id, &modified_student.class_id, modified_student.name, &modified_student.score1, &modified_student.score2, &modified_student.score3);
// 检查学号是否存在,如果不存在,输出原有三个学生信息并退出程序
int found = 0;
for (int i = 0; i < num_students; i++) {
if (modified_student.student_id == students[i].student_id) {
found = 1;
students[i] = modified_student;
break;
}
}
if (!found) {
printf("该学生信息不存在,输出原有三个学生信息并退出程序:\n");
for (int i = 0; i < num_students; i++) {
printf("%d %d %s %.1f %.1f %.1f\n", students[i].student_id, students[i].class_id, students[i].name, students[i].score1, students[i].score2, students[i].score3);
}
return 0;
}
// 对新数据进行排序
qsort(students, num_students, sizeof(struct Student), compareStudents);
// 输出学生信息
for (int i = 0; i < num_students; i++) {
if (i == 0 || students[i].class_id != students[i - 1].class_id) {
printf("%d %d %s %.1f %.1f %.1f", students[i].student_id, students[i].class_id, students[i].name, students[i].score1, students[i].score2, students[i].score3);
} else {
printf(" %d %s %.1f %.1f %.1f", students[i].student_id, students[i].name, students[i].score1, students[i].score2, students[i].score3);
}
if (i == num_students - 1) {
printf(" modified\n");
} else {
printf("\n");
}
}
return 0;
}