(4)基于结构体,编写一个班级成绩排序系统。 定义一个结构体 Student ,包含姓名( name ,字符串)、学号( id , int 型)、3门课程成绩( score , double 数组)、平均成绩( avg _ score , double 型)。输入每个学生的姓名、学号、3 门课程成绩。计算平均成绩,按平均成绩由高到低排序后输出。 填写下列程序。 # include < stdio . h > # define N 3/*学生人数*/ struct Student void input _ student info ( struct Student * p , int n ) int i ; for ( i -0:i< n ; i ++_ printf " printf (" student % dn ", i +1); printf (" name :"); gets ( printf (" id :"); scanf ("% d " printf (" scores :"); scanf ("%1f%1f%1f", printf ("- fflush ( stdin ); - An "); An "); void calculate _ avg _ score ( struct Student * p . int n ) inti ; for ( i -0; i < n ; itt , p -> avg _ score = void print student info ( struct Student * p , int n ) int i ; printf (" -\ n "); printf ("%15s%8s%8s%8s%8s%12sn"," name "," id "," scorel ","score2","score3"," avg score "); for ( i =0; i < n ; itt , ptt )
时间: 2024-04-28 15:20:42 浏览: 115
#include <stdio.h>
#include <string.h>
#define N 3
// 定义结构体
struct Student {
char name[20]; // 姓名
int id; // 学号
double score[3]; // 3门课程成绩
double avg_score; // 平均成绩
};
// 输入每个学生的信息
void input_student_info(struct Student *p, int n) {
int i;
for (i = 0; i < n; i++, p++) {
printf("student %d\n", i+1);
printf("name: ");
getchar(); // 清空输入缓存
gets(p->name);
printf("id: ");
scanf("%d", &p->id);
printf("scores: ");
scanf("%lf%lf%lf", &p->score[0], &p->score[1], &p->score[2]);
}
}
// 计算每个学生的平均成绩
void calculate_avg_score(struct Student *p, int n) {
int i;
for (i = 0; i < n; i++, p++) {
p->avg_score = (p->score[0] + p->score[1] + p->score[2]) / 3.0;
}
}
// 按平均成绩由高到低排序后输出
void print_student_info(struct Student *p, int n) {
int i, j;
struct Student temp;
// 冒泡排序
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-1-i; j++) {
if (p[j].avg_score < p[j+1].avg_score) {
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
// 输出排序结果
printf("\n%15s%8s%8s%8s%8s%12s\n", "name", "id", "score1", "score2", "score3", "avg score");
for (i = 0; i < n; i++, p++) {
printf("%15s%8d%8.1lf%8.1lf%8.1lf%12.1lf\n", p->name, p->id, p->score[0], p->score[1], p->score[2], p->avg_score);
}
}
int main() {
struct Student stu[N];
input_student_info(stu, N); // 输入每个学生的信息
calculate_avg_score(stu, N); // 计算每个学生的平均成绩
print_student_info(stu, N); // 按平均成绩由高到低排序后输出
return 0;
}
阅读全文