请用C++完成下面的实验创建一个Student类,其属性包括学号和成绩。在main函数中建立一个Student对象数组,内放5个学生对象,输入这5个学生对象的学号和成绩,并调用函数max找出这5个学生中成绩最高者,输出其学号和成绩。max函数用指向Student对象的指针做函数参数。
时间: 2023-05-23 18:07:31 浏览: 86
#include <iostream>
using namespace std;
class Student {
public:
int number;
double score;
Student(int n = 0, double s = 0.0) {
number = n;
score = s;
}
};
Student* max(Student* arr, int len) {
if (len <= 0) return nullptr;
Student* maxstu = &arr[0];
for (int i = 1; i < len; i++) {
if (arr[i].score > maxstu->score) {
maxstu = &arr[i];
}
}
return maxstu;
}
int main() {
Student arr[5];
for (int i = 0; i < 5; i++) {
cout << "请输入第" << i + 1 << "个学生的学号和成绩:";
cin >> arr[i].number >> arr[i].score;
}
Student* maxstu = max(arr, 5);
cout << "成绩最高的学生是:" << maxstu->number << ",成绩为:" << maxstu->score << endl;
return 0;
}
阅读全文