输入5个学生3门课的成绩存入结构体数组中;(2)输出学生信息;(3)求每个学生的平均分;(4)按平均分从高到低排列;(5)按平均分求每个学生的名次。要求:用结构体数组存放学生信息,每个功能都用函数实现。用c语言编写。
时间: 2023-05-18 11:05:36 浏览: 57
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENT 5
#define MAX_COURSE 3
typedef struct {
char name[20];
int scores[MAX_COURSE];
float average;
int rank;
} Student;
void input_scores(Student students[]);
void calculate_average(Student students[]);
void sort_by_average(Student students[]);
void calculate_rank(Student students[]);
void output_students(Student students[]);
int main() {
Student students[MAX_STUDENT];
input_scores(students);
calculate_average(students);
sort_by_average(students);
calculate_rank(students);
output_students(students);
return 0;
}
void input_scores(Student students[]) {
for (int i = 0; i < MAX_STUDENT; i++) {
printf("请输入第%d个学生的姓名:", i + 1);
scanf("%s", students[i].name);
for (int j = 0; j < MAX_COURSE; j++) {
printf("请输入%s的第%d门课的成绩:", students[i].name, j + 1);
scanf("%d", &students[i].scores[j]);
}
}
}
void calculate_average(Student students[]) {
for (int i = 0; i < MAX_STUDENT; i++) {
float sum = 0;
for (int j = 0; j < MAX_COURSE; j++) {
sum += students[i].scores[j];
}
students[i].average = sum / MAX_COURSE;
}
}
void sort_by_average(Student students[]) {
for (int i = 0; i < MAX_STUDENT - 1; i++) {
for (int j = i + 1; j < MAX_STUDENT; j++) {
if (students[i].average < students[j].average) {
Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
void calculate_rank(Student students[]) {
int rank = 1;
for (int i = 0; i < MAX_STUDENT; i++) {
if (i > 0 && students[i].average < students[i - 1].average) {
rank++;
}
students[i].rank = rank;
}
}
void output_students(Student students[]) {
printf("学生姓名\t课程1\t课程2\t课程3\t平均分\t名次\n");
for (int i = 0; i < MAX_STUDENT; i++) {
printf("%s\t", students[i].name);
for (int j = 0; j < MAX_COURSE; j++) {
printf("%d\t", students[i].scores[j]);
}
printf("%.2f\t%d\n", students[i].average, students[i].rank);
}
}
阅读全文