5)建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数 max,用对象指针做函数参数,在max中找出5个学生中成绩最高者,并 输出其学号。c++用类的方法
时间: 2024-02-29 16:55:35 浏览: 149
好的,让我来解释一下这个问题。
首先,我们需要定义一个学生类,包括学号和成绩这两个成员变量。代码如下:
```cpp
class Student {
public:
int id;
int score;
};
```
然后,我们可以创建一个包含5个学生数据的对象数组。代码如下:
```cpp
Student students[5] = {
{1, 80},
{2, 75},
{3, 90},
{4, 85},
{5, 95}
};
```
接下来,我们需要写一个 max 函数,用于找出这5个学生中成绩最高者的学号。代码如下:
```cpp
int max(Student *students, int n) {
int maxScore = students[0].score;
int maxId = students[0].id;
for (int i = 1; i < n; i++) {
if (students[i].score > maxScore) {
maxScore = students[i].score;
maxId = students[i].id;
}
}
return maxId;
}
```
最后,我们只需要调用这个 max 函数,传入学生对象数组的指针和学生数量即可。代码如下:
```cpp
int main() {
int maxId = max(students, 5);
cout << "最高分的学生学号是:" << maxId << endl;
return 0;
}
```
这样就可以输出成绩最高的学生的学号了。
阅读全文
相关推荐












