采用结构体变量的方法保存学生成绩,有五个学生,每个学生有3门课的成绩,从键盘输入相关
数据(包括:学号,姓名和三门课程的成绩)
,计算出平均成绩。
2.
采用结构体数组的方法保存学生成绩,完成练习1
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_LEN 100 /*数组长度*/
/*定义学生结构体*/
typedef struct {
int no; /*学号*/
float score1; /*成绩1*/
float score2; /*成绩2*/
float score3; /*成绩3*/
float totalScore; /*总分*/
float averageScore; /*平均分*/
} student;
/*输入学生信息*/
void inputInfo (student stu[], int stuIndex) {
int i;
printf ("第%d名学生↓\n", stuIndex+1);
printf ("学号:");
scanf ("%d",&stu[stuIndex].no);
printf ("成绩1:");
scanf ("%f",&stu[stuIndex].score1);
printf ("成绩2:");
scanf ("%f",&stu[stuIndex].score2);
printf ("成绩3:");
scanf ("%f",&stu[stuIndex].score3);
putchar ('\n');
}
/*计算平均成绩*/
void calculationScore (student stu[], int stuIndex) {
stu[stuIndex].totalScore=stu[stuIndex].score1+stu[stuIndex].score2+stu[stuIndex].score3;
stu[stuIndex].averageScore=stu[stuIndex].totalScore/3;
} /*输出学生成绩*/
void printInfo (student stu[], int stuIndex) {
int i;
printf ("%d\t",stu[stuIndex].no);
printf ("%.2f\t",stu[stuIndex].score1);
printf ("%.2f\t",stu[stuIndex].score2);
printf ("%.2f\t",stu[stuIndex].score3);
printf ("%.2f",stu[stuIndex].averageScore);
putchar ('\n');
}
int main (void) {
int stuNum=5,i;
student stu[ARRAY_LEN];
/*输入、计算*/
puts ("请输入学生信息:");
putchar ('\n');
for (i=0; i<stuNum; i++) {
inputInfo (stu,i);
calculationScore (stu,i);
}
putchar ('\n');
printf ("%d名学生成绩输入完毕!", stuNum);
putchar ('\n');
puts ("================================================\n");
/*输出*/
puts ("学号\t成绩1\t成绩2\t成绩3\t平均成绩");
for (i=0; i<stuNum; i++)
printInfo (stu,i);
getch (); /*屏幕暂留*/
return 0;
}
运行结果: