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.

94 lines
2.6 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 <string.h>
#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;
}