结构体求成绩平均分问题
有10个学生,每个学生的数据包括学号、姓名、3门课程的成绩,从键盘输入10个学生数据,要求输出3门课程总平均成绩,以及最高分的学生数据。
#include <stdio.h>
#define N 2
struct student
{
int num;
char name[10];
float score[3];
};
main()
{
struct student stu[10]; //结构体数组
int i,j;
float averscore[N],sum,highscore;
for(i=0;i<N;i++)
{
sum=0;
scanf("%d%s",&stu[i].num,stu[i].name);
for(j=1;j<=3;j++)
{
scanf("%f",&stu[i].score[j]);
sum+=stu[i].score[j];
}
averscore[i]=sum/3;
printf("第%d学生的3门课程总平均成绩:%f\n",stu[i].num,averscore[i]);
}
highscore=averscore[0]; //若第1名平均分为最高
for(i=1;i<N;i++) //
if(averscore[i]>highscore)
highscore=averscore[i];
printf("最高分的学生学号为%d,姓名%s,3门课程成绩%f,平均成绩%5.2f%5.2f%5.2f",
stu[i].num,stu[i].name,stu[i].score[0],stu[i].score[1],stu[i].score[2]);
}
搞了半天 不知道错哪里了 头都晕了
[解决办法]
#include <stdio.h>
#define N 2
struct student
{
int num;
char name[10];
float score[3];
};
main()
{
struct student stu[10]; //结构体数组
int i,j,flat;
float averscore[N],sum,highscore;
for(i=0;i<N;i++)
{
sum=0;
scanf("%d %s",&stu[i].num,stu[i].name);
for(j=1;j<=3;j++)
{
scanf(" %f",&stu[i].score[j]);
sum+=stu[i].score[j];
}
averscore[i]=sum/3;
printf("第%d学生的3门课程总平均成绩:%f\n",stu[i].num,averscore[i]);
}
highscore=0; //若第1名平均分为最高
for (i=0;i<N;i++)
{if (averscore[i]>=highscore) {highscore=averscore[i]; flat=i;}}
i=flat;
printf("最高分的学生学号为%d,姓名%s,第一门课程成绩%3.2f ,第二门课程成绩%3.2f,第三门课程成绩%3.2f,平均成绩%5.2f",
stu[i].num,stu[i].name,stu[i].score[1],stu[i].score[2],stu[i].score[3],averscore[i]);
}
这是我改了以后能运行的,你的思维很混乱啊,先想好算法再写程序吧。你对比一下,改的是输入格式和最后那一段。
[解决办法]
有几个问题,我觉得
定义数组要从 0 开始 这样比较好把
还有 最高分的学号应该存储到另外一个变量中。
我QQ516668272 我也喜欢计算机,如果有兴趣的话可以互相交流
#include <stdio.h>
#define N 2
struct student
{
int num;
char name[10];
float score[3];
};
void main()
{
struct student stu[10]; //结构体数组
int i,j,maxi;
float averscore[N],sum,highscore;
for(i=0;i<N;i++)
{
sum=0;
printf("请输入学生的学号和姓名\n");
scanf("%d%s",&stu[i].num,stu[i].name);
printf("请分别输入学生的3门成绩");
for(j=0;j<3;j++)//这行需要修改!!!!
{
scanf("%f",&stu[i].score[j]);
sum+=stu[i].score[j];
}
averscore[i]=sum/3.0;
printf("第%d学生的3门课程总平均成绩:%f\n",stu[i].num,averscore[i]);
}
highscore=averscore[0]; //若第1名平均分为最高
maxi=0;//
for(i=0;i<N;i++) //这里需要修改!!
if(averscore[i]>highscore)
{
maxi=i;//
highscore=averscore[i];
}
printf("最高分的学生学号为%d,姓名%s,3门课程成绩%f,平均成绩%5.2f%5.2f%5.2f",
stu[maxi].num,stu[maxi].name,averscore[maxi],stu[maxi].score[0],stu[maxi].score[1],stu[maxi].score[2]);
}