某班有10个学生,定义一个结构体数组,存放学生的编号(不同学生的编号不相同)、姓名、数学成绩,成绩保留1位小数,成绩范围[0.0,100.0]; 要求:写三个函数,分别完成 1、将输入的10学生的编号、姓名和成绩保存到结构体数组中,需要有数据合法性验证; 2、将学生按成绩由大到小进行排序,成绩相同的按学号从小到大排序; 3、按排序后的结果进行输出;
时间: 2023-04-07 15:01:47 浏览: 322
我可以回答这个问题。以下是代码示例:
#include <stdio.h>
#include <string.h>
#define MAX_STUDENT_NUM 10
typedef struct {
int id;
char name[20];
float score;
} Student;
void input_students(Student students[]) {
int i;
for (i = 0; i < MAX_STUDENT_NUM; i++) {
printf("请输入第%d个学生的编号、姓名和成绩:\n", i + 1);
scanf("%d %s %f", &students[i].id, students[i].name, &students[i].score);
if (students[i].id < 1 || students[i].id > MAX_STUDENT_NUM) {
printf("学生编号必须在1到%d之间,请重新输入!\n", MAX_STUDENT_NUM);
i--;
} else if (students[i].score < 0.0 || students[i].score > 100.0) {
printf("学生成绩必须在0.0到100.0之间,请重新输入!\n");
i--;
}
}
}
void sort_students(Student students[]) {
int i, j;
Student temp;
for (i = 0; i < MAX_STUDENT_NUM - 1; i++) {
for (j = i + 1; j < MAX_STUDENT_NUM; j++) {
if (students[i].score < students[j].score ||
(students[i].score == students[j].score && students[i].id > students[j].id)) {
temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
void output_students(Student students[]) {
int i;
printf("学生排名如下:\n");
for (i = 0; i < MAX_STUDENT_NUM; i++) {
printf("第%d名:编号=%d,姓名=%s,成绩=%.1f\n", i + 1, students[i].id, students[i].name, students[i].score);
}
}
int main() {
Student students[MAX_STUDENT_NUM];
input_students(students);
sort_students(students);
output_students(students);
return 0;
}
阅读全文