一个关于c语言结构体数组的问题.

2025-01-02 06:36:51
推荐回答(2个)
回答1:

#include
#include//exit()包含在stdlib.h文件中
struct student
{
char xuehao[7],name[25];
float score[3],average; //结构体中不能赋初值,average=0改为average
};
void main()
{
struct student stu[5];
int j=0;
struct student f(struct student *);
for(j=0;j<=4;j++)
stu[j]=f(&stu[j]); //stu1[]没有定义,不能用,改为&stu[j]
printf("学号\t姓名\t成绩1\t成绩2\t成绩3\t平均成绩\n"); //这儿)前面少了个"号
for(j=0;j<=4;j++)
{
printf("%s\t%s\t%.1f\t%.1f\t%1f\t%f\n",
stu[j].xuehao,stu[j].name,
stu[j].score[0],stu[j].score[1],
stu[j].score[2],stu[j].average);
}
}

struct student f(struct student *p)
{
struct student stu1[5];
int i=0,j=0;
for(j=0;j<=4;j++)
{

printf("stu%d name:",j+1);
scanf("%s",p->name);
printf("stu%d xuehao:",j+1);
scanf("%s",p->xuehao);
for(i=0;i<=2;i++)
{
printf("please input stu%d score%d:",j,i); //这儿j前面少了个,号
scanf("%f",&p->score[i]);
if(p->score[i]<0||p->score[i]>100)
{
printf("score input error!");
exit(0);
}

}
p->average=(p->score[0]+p->score[1]+p->score[2])/3;//这儿应该使用p->变量的形式
return (stu1[j]);
}
return stu1[j];//这儿即使 if 不成立也应该返回函数类型的值
}

回答2:

#include
struct student
{
char xuehao[7],name[25];
float score[3],average; //在strtic里不能初始化变量
};
void main()
{
struct student stu[5];
int j=0;
struct student f(struct student *);
for(j=0;j<=4;j++)
stu[j]=f(&stu[j]); //str1[j]那里来的变量,改成str[j]
printf("学号\t姓名\t成绩1\t成绩2\t成绩3\t平均成绩\n"); //后面缺少"
for(j=0;j<=4;j++)
{
printf("%s\t%s\t%.1f\t%.1f\t%1f\t%f\n",
stu[j].xuehao,stu[j].name,
stu[j].score[0],stu[j].score[1],
stu[j].score[2],stu[j].average);
}
}

struct student f(struct student *p)
{
struct student stu1[5];
int i=0,j=0;
for(j=0;j<=4;j++)
{

printf("stu%d name:",j+1);
scanf("%s",p->name);
printf("stu%d xuehao:",j+1);
scanf("%s",p->xuehao);
for(i=0;i<=2;i++)
{
printf("please input stu%d score%d:",j,i); //j变量前没有 ,
scanf("%f",&p->score[i]);
if(p->score[i]<0||p->score[i]>100)
{
printf("score input error!");
//exit(); //退出码有问题
}
}
p->average=(p->score[0]+p->score[1]+p->score[2])/3; //使用p->成员
return (stu1[j]);
}
}