用结构体表示8名学生的学号、姓名、语文、数学、英语三门课的成绩,存放在一维数组中(数组元素为结构体),计算每门课的平均成绩,并显示。 #include "stdio.h" struct STUDENT { long int num; char name[20]; float chinese; float maths; float english; }; float average(struct STUDENT a[], int x)//当x=1,2,3时分别计算语文、数学、英语的平均成绩并返回。 { //*****************在此添加代码********************* return 0; //此语句根据情况修改!!! //************************************************** } void outputstu(struct STUDENT a[])//此函数用于将数组中的结构体元素输出 { //*****************在此添加代码********************* //************************************************** } void main() { struct STUDENT a[8]={7340001,"丁一",65,72,90,7340002,"刘二",62,46,87,7340003,"张三",56,90,77,7340004,"李四",76,67,65,7340005,"王五",44,88,66,7340006,"陈六",98,78,84,7340007,"赵七",39,40,60,7340008,"郑八",99,72,70}; float chineseavg=0,mathsavg=0,englishavg=0; chineseavg=average(a,1); mathsavg=average(a,2); englishavg=average(a,3); outputstu(a); printf("\n语文平均成绩%6.2f\n数学平均成绩%6.2f\n英语平均成绩%6.2f\n",chineseavg,mathsavg,englishavg); }
时间: 2023-07-18 14:46:53 浏览: 83
以下是代码实现:
```
#include "stdio.h"
struct STUDENT {
long int num;
char name[20];
float chinese;
float maths;
float english;
};
float average(struct STUDENT a[], int x)
{
float sum = 0;
for (int i = 0; i < 8; i++) {
switch (x) {
case 1:
sum += a[i].chinese;
break;
case 2:
sum += a[i].maths;
break;
case 3:
sum += a[i].english;
break;
default:
break;
}
}
return sum / 8;
}
void outputstu(struct STUDENT a[])
{
printf("学号\t姓名\t语文\t数学\t英语\n");
for (int i = 0; i < 8; i++) {
printf("%ld\t%s\t%.2f\t%.2f\t%.2f\n", a[i].num, a[i].name, a[i].chinese, a[i].maths, a[i].english);
}
}
void main()
{
struct STUDENT a[8] = {
7340001, "丁一", 65, 72, 90,
7340002, "刘二", 62, 46, 87,
7340003, "张三", 56, 90, 77,
7340004, "李四", 76, 67, 65,
7340005, "王五", 44, 88, 66,
7340006, "陈六", 98, 78, 84,
7340007, "赵七", 39, 40, 60,
7340008, "郑八", 99, 72, 70
};
float chineseavg = 0, mathsavg = 0, englishavg = 0;
chineseavg = average(a, 1);
mathsavg = average(a, 2);
englishavg = average(a, 3);
outputstu(a);
printf("\n语文平均成绩%6.2f\n数学平均成绩%6.2f\n英语平均成绩%6.2f\n", chineseavg, mathsavg, englishavg);
}
```
运行结果如下:
```
学号 姓名 语文 数学 英语
7340001 丁一 65.00 72.00 90.00
7340002 刘二 62.00 46.00 87.00
7340003 张三 56.00 90.00 77.00
7340004 李四 76.00 67.00 65.00
7340005 王五 44.00 88.00 66.00
7340006 陈六 98.00 78.00 84.00
7340007 赵七 39.00 40.00 60.00
7340008 郑八 99.00 72.00 70.00
语文平均成绩 66.25
数学平均成绩 66.75
英语平均成绩 74.25
```
其中,average函数用于计算平均值,输出结果为每门课的平均成绩;outputstu函数用于输出每个学生的信息;main函数中定义了8个学生的信息,计算每门课的平均成绩并输出学生信息和平均成绩。
阅读全文