根据给定的程序,写成相关的成员函数,完成指定功能。
函数接口定义:
定义max函数,实现输出最高成绩对应的学号以及最高成绩值。
裁判测试程序样例:
#include <iostream> 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* p) //接受一个指向Student类型的指针p作为参数。
{Student *max, *p1; //定义了两个指向Student类型的指针变量max和p1。max = p; //将max指针初始化为传入的p指针,即假设第一个学生的分数就是目前找到的最高分。for(p1 = p+1; p1 < p+5; p1++) //从p+1开始(即第二个学生),直到p+4(即第五个学生)if(max->score < p1->score){ //如果当前max指向的学生的分数小于p1指向的学生的分数max->num = p1->num; max->score = p1->score;} //将max指针重新指向分数更高的学生,并更新max指针所指向的学生的编号和分数。cout << max->num << " " << max->score;} //最后输出最高分学生的编号和分数。