6-2 输出最大值 (10分)
根据给定的程序,写成相关的成员函数,完成指定功能。
函数接口定义:
定义max函数,实现输出最高成绩对应的学号以及最高成绩值。
裁判测试程序样例:
#include
using namespace std;
class Student
{public:
Student(int n,float s):num(n),score(s){}
int num;
float score;
};
int main()
{Student stud[5]={
Student(101,78.5),Student(102,85.5),Student(103,98.5),
Student(104,100.0),Student(105,95.5)};
void max(Student* );
Student * p=&stud[0];
max( p );
return 0;
}
/* 请在这里填写答案 */
输入样例:
无
输出样例:
104 100
-----------------------------------------------------分割线--------------------------------------------------
题目分析
- 本题主函数内 语句void max(Student* );
为函数原型声明。 - 主函数内定义了Student类的指针p,并将p指向对象数组Student。
- 自定义函数max使用了该指针p。
综上分析,我们可以在自定义函数max()中,定义指针p1用于控制循环结束,定义指针max寻找我们所需最大值。
void max(Student* p)
{
Student *max, *p1;
max = p;
for(p1 = p+1; p1 < p+5; p1++)
if(max->score < p1->score){
max->num = p1->num;
max->score = p1->score;
}
cout << max->num << " " << max->score;
}