c语言 编写程序,用结构体存放学生的若干信息,包括学号、姓名和3门课程的分数,从键盘输入数据,输出每门课程的总平均分,以及最高分的学生的完整数据。
时间: 2024-03-25 17:41:56 浏览: 13
好的,以下是C语言代码实现:
```c
#include <stdio.h>
#include <string.h>
#define N 3 // 学生数量
#define M 3 // 课程数量
struct student {
char id[10]; // 学号
char name[20]; // 姓名
float score[M]; // 3门课程的分数
float avg; // 平均分
};
void input(struct student *stu); // 输入学生信息函数声明
void calcAvg(struct student *stu); // 计算平均分函数声明
void findMax(struct student *stu); // 查找最高分学生函数声明
int main() {
struct student stu[N];
int i;
for (i = 0; i < N; i++) {
input(&stu[i]); // 输入学生信息
}
for (i = 0; i < N; i++) {
calcAvg(&stu[i]); // 计算每个学生的平均分
}
printf("每门课程的总平均分:\n");
float sum[M] = {0}; // 每门课程的总分数
for (i = 0; i < N; i++) {
sum[0] += stu[i].score[0];
sum[1] += stu[i].score[1];
sum[2] += stu[i].score[2];
}
printf("语文:%.2f,数学:%.2f,英语:%.2f\n", sum[0]/N, sum[1]/N, sum[2]/N);
findMax(stu); // 查找最高分学生
return 0;
}
void input(struct student *stu) {
printf("请输入学生的学号:");
scanf("%s", stu->id);
printf("请输入学生的姓名:");
scanf("%s", stu->name);
printf("请输入学生的语文、数学、英语成绩:");
scanf("%f%f%f", &stu->score[0], &stu->score[1], &stu->score[2]);
}
void calcAvg(struct student *stu) {
float sum = 0;
int i;
for (i = 0; i < M; i++) {
sum += stu->score[i];
}
stu->avg = sum / M;
}
void findMax(struct student *stu) {
int i, maxIndex = 0;
float maxScore = stu[0].score[0];
for (i = 0; i < N; i++) {
if (stu[i].score[0] > maxScore) {
maxIndex = i;
maxScore = stu[i].score[0];
} else if (stu[i].score[1] > maxScore) {
maxIndex = i;
maxScore = stu[i].score[1];
} else if (stu[i].score[2] > maxScore) {
maxIndex = i;
maxScore = stu[i].score[2];
}
}
printf("最高分学生的完整数据如下:\n");
printf("学号:%s\n", stu[maxIndex].id);
printf("姓名:%s\n", stu[maxIndex].name);
printf("语文:%.2f,数学:%.2f,英语:%.2f,平均分:%.2f\n", stu[maxIndex].score[0], stu[maxIndex].score[1], stu[maxIndex].score[2], stu[maxIndex].avg);
}
```
说明:
这段代码首先定义一个结构体类型student,包括学号、姓名、3门课程的分数和平均分,然后在主函数中定义一个包含N个学生的数组。接着分别调用input函数输入学生信息,calcAvg函数计算每个学生的平均分。
在计算每门课程的总平均分时,我们使用一个长度为M的数组sum来存储每门课程的总分数,然后遍历所有学生,将每个学生对应课程的分数累加到sum数组相应元素上,最后输出每门课程的总平均分。
在查找最高分学生时,我们遍历所有学生的分数,找到最高分对应的学生,然后输出该学生的完整数据。
希望能够帮到您。