关于结构体的一个有关问题,算法简单,就是不知道哪儿出错了
关于结构体的一个问题,算法简单,就是不知道哪儿出错了
#include"stdio.h"
int main(){
struct xj{
int xh;
char name[10];
struct cj{
int yw;
int sx;
int yy;
}stu_cj;/*再在结构体里定义一个结构体类型cj,并定义一个结构体变量stu_cj用来存放三门功课成绩*/
int zcj;
};/*定义结构体XJ类型*/
struct xj stu[10];/*定义结构体变量stu数组,有10个结构体变量*/
int i=0,n,max,k=0;
printf("请输入你要输入几个同学的成绩\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("请按如下格式输入第%d个同学学号,姓名,语文成绩 数学成绩 英语成绩\n",i+1);
scanf("%d,%s,%d %d %d",&stu[i].xh,&stu[i].name,&stu[i].stu_cj.yw,&stu[i].stu_cj.sx,&stu[i].stu_cj.yy);
};
for(i=0;i<n;i++)
{
stu[i].zcj=stu[i].stu_cj.yw+stu[i].stu_cj.sx+stu[i].stu_cj.yy;
printf("第%d个同学平均成绩:%d",i+1,stu[i].zcj/3);
};/*计算每个同学的总成绩,然后按平均成绩输出*/
max=stu[0].zcj;
for(i=1;i<n;i++)
{
if(max<stu[i].zcj)
{max=stu[i].zcj;
k=i;};/*用K记录成绩最高同学的下标,并在下行输出该同学的所有录入信息*/
}
printf("最高成绩学生的学号:%d姓名:%s三门课成绩:%d%d%d平均成绩是:%d\n",stu[k].xh,stu[k].name,stu[i].stu_cj.yw,stu[i].stu_cj.sx,stu[i].stu_cj.yy,stu[k].zcj/3);
}
------解决方案--------------------
帮你改好了,你看看
#include"stdio.h"
int main(){
struct xj{
int xh;
char name[10];
struct cj{
int yw;
int sx;
int yy;
}stu_cj;/*再在结构体里定义一个结构体类型cj,并定义一个结构体变量stu_cj用来存放三门功课成绩*/
int zcj;
};/*定义结构体XJ类型*/
struct xj stu[10];/*定义结构体变量stu数组,有10个结构体变量*/
int i=0,n,max,k=0;
printf("请输入你要输入几个同学的成绩\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("请按如下格式输入第%d个同学学号,姓名,语文成绩 数学成绩 英语成绩\n",i+1);
scanf("%d,%s,%d %d %d",&stu[i].xh,&stu[i].name,&stu[i].stu_cj.yw,&stu[i].stu_cj.sx,&stu[i].stu_cj.yy);
};
for(i=0;i<n;i++)
{
stu[i].zcj=stu[i].stu_cj.yw+stu[i].stu_cj.sx+stu[i].stu_cj.yy;
printf("第%d个同学平均成绩:%d",i+1,stu[i].zcj/3);
};/*计算每个同学的总成绩,然后按平均成绩输出*/
max=stu[0].zcj;
for(i=1;i<n;i++)
{
if(max<stu[i].zcj)
{max=stu[i].zcj;
k=i;};/*用K记录成绩最高同学的下标,并在下行输出该同学的所有录入信息*/
}
printf("最高成绩学生的学号:%d姓名:%s三门课成绩:%d%d%d平均成绩是:%d\n",stu[k].xh,stu[k].name,stu[i].stu_cj.yw,stu[i].stu_cj.sx,stu[i].stu_cj.yy,stu[k].zcj/3);
}
------解决方案--------------------
帮你改好了,你看看
- C/C++ code
#include"stdio.h" struct xj { int xh; char name[10]; struct cj { int yw; int sx; int yy; }stu_cj;/*再在结构体里定义一个结构体类型cj,并定义一个结构体变量stu_cj用来存放三门功课成绩*/ int zcj; };/*定义结构体XJ类型*/ int main() { struct xj stu[10];/*定义结构体变量stu数组,有10个结构体变量*/ int i=0,n,max,k=0; printf("请输入你要输入几个同学的成绩\n"); scanf("%d",&n); for(i=0;i<n;i++) { printf("请按如下格式输入第%d个同学学号 姓名 语文成绩 数学成绩 英语成绩\n",i+1); scanf("%d",&stu[i].xh); getchar(); scanf("%s",stu[i].name); getchar(); scanf("%d %d %d",&stu[i].stu_cj.yw,&stu[i].stu_cj.sx,&stu[i].stu_cj.yy); //这里有个,写成中文了, 数组名就是首地址了,不用加& } for(i=0;i<n;i++) { stu[i].zcj=stu[i].stu_cj.yw+stu[i].stu_cj.sx+stu[i].stu_cj.yy; printf("第%d个同学平均成绩:%d\n",i+1,stu[i].zcj/3); }/*计算每个同学的总成绩,然后按平均成绩输出*///for之后不用; max=stu[0].zcj; for(i=1;i<n;i++) { if(max<stu[i].zcj) { max=stu[i].zcj; k=i;/*用K记录成绩最高同学的下标,并在下行输出该同学的所有录入信息*/ } }//for之后不用; printf("最高成绩学生的学号:%d姓名:%s三门课成绩:%d %d %d平均成绩是:%d\n", stu[k].xh,stu[k].name,stu[k].stu_cj.yw,stu[k].stu_cj.sx,stu[k].stu_cj.yy,stu[k].zcj/3); //这里的成绩都是k学生的,不该用i,经过for循环,i都等于n了,肯定是溢出的随机数 //这里有个,写成中文了 return 0; }