64,662
社区成员
发帖
与我相关
我的任务
分享
//2、编写一个函数print,打印一个学生的成绩数组,该数组中有5个学生的数据,每个学生的数据包括
//num学号,name姓名,score[3]三门课的成绩。用主函数输入这些数据,用print函数输出这些数据。
#include<iostream>
using namespace std;
struct Student
{
int num;
char name[20];
int score[3];
};
Student s[5];
void print (Student *p);
int main()
{
int j = 0;
for (int i = 0; i < 5; i ++)
{
cout<<"please input the num and the name of the student:"<<i + 1;
cin>>s[i].num>>s[i].name;
for (int j = 0; j <3; j ++)
{
cout<<"please input the score of subject"<<j + 1<<" of the student:"<<i + 1;
cin>>s[i].score[j];
}
}
Student *p = s;
print(p);
return 0;
}
void print (Student *p)
{
int j = 0;
for (int i = 0; i < 5; i ++)
{
cout<<"num: "<<*p -> s[i].num<<'\t'<<"name: "<<s[i].name<<'\t';
for (int j = 0; j <3; j ++)
cout<<"scores: "<<s[i].score[j]<<'\t';
cout<<endl;
}
return;
}
//2、编写一个函数print,打印一个学生的成绩数组,该数组中有5个学生的数据,每个学生的数据包括
//num学号,name姓名,score[3]三门课的成绩。用主函数输入这些数据,用print函数输出这些数据。
#include<iostream>
using namespace std;
struct Student
{
int num;
char name[20];
int score[3];
};
struct Student s[5];
void print (Student *p);
int main()
{
int j = 0;
for (int i = 0; i < 5; i ++)
{
cout<<"please input the num and the name of the student:"<<i + 1;
cin>>s[i].num>>s[i].name;
for (int j = 0; j <3; j ++)
{
cout<<"please input the score of subject"<<j + 1<<" of the student:"<<i + 1;
cin>>s[i].score[j];
}
}
struct Student *p = s;
print(p);
return 0;
}
void print (struct Student *p)
{
int j = 0;
for (int i = 0; i < 5; i ++)
{
cout<<"num: "<<p[i].num<<'\t'<<"name: "<<s[i].name<<'\t';
for (int j = 0; j <3; j ++)
cout<<"scores: "<<s[i].score[j]<<'\t';
cout<<endl;
}
return;
}
楼主有几个错误的地方:
1,我记得结构体的声明和定义如果没有用typedef定义别名就需要在前面加上struct(此处存疑)
2,你传的是数组的首地址,传进去后直接用就行了,你用*p->s[i].num这一句明显是对指针和数组理解不够。#include<iostream>
using namespace std;
struct Student
{
int num;
char name[20];
int score[3];
};
void print (Student s[5])
{
for (int i = 0; i < 5; i++)
{
cout<<"num: "<<s[i].num<<","<<"name: "<<s[i].name<<",";
for (int j = 0; j <3; j ++)
cout<<"scores: "<<s[i].score[j];
cout<<endl;
}
}
int main()
{
Student s[5];
for (int i = 0; i < 5; i ++)
{
cout<<"please input the num and the name of the student:"<<i + 1<<endl;
cin>>s[i].num>>s[i].name;
for (int j = 0; j <3; j ++)
{
cout<<"please input the score of subject"<<j + 1<<" of the student:"<<i + 1;
cin>>s[i].score[j];
}
}
print(s);
return 0;
}
没明白楼主为什么要用指针……
for (int i = 0; i < 5; i ++)
{
cout<<"num: "<<s[i].num<<'\t'<<"name: "<<s[i].name<<'\t';
for (int j = 0; j <3; j ++)
cout<<"scores: "<<s[i].score[j]<<'\t';
cout<<endl;
}
在你的代码里void print (Student *p)的参数 p 是没用的,按照print的声明,print只是输出一个学生的成绩,而你的代码print输出了全部学生的成绩。
建议:
1、不要使用全局变量 Student s[5];,将其改为 main的局部变量,通过print输出每个学生的成绩。
2、pring改为
void print (Student *p)
{
int j = 0;
cout<<"num: "<<p ->num<<'\t'<<"name: "<<p->name<<'\t';
for (int j = 0; j <3; j ++)
cout<<"scores: "<<p->score[j]<<'\t';
cout<<endl;
return;
}
在main中循环调用print函数。