建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数max,用指向对象的指针作函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号。
时间: 2024-05-15 13:18:55 浏览: 6
很高兴能和你聊天!关于你的问题,我可以帮你解答。
以下是代码实现:
```
#include <iostream>
using namespace std;
class Student {
public:
int num;
double score;
};
void max(Student *stu) {
double maxScore = 0;
int maxNum = 0;
for (int i = 0; i < 5; i++) {
if (stu[i].score > maxScore) {
maxScore = stu[i].score;
maxNum = stu[i].num;
}
}
cout << "最高分学生学号: " << maxNum << endl;
}
int main() {
Student stu[5] = {{101, 98}, {102, 76}, {103, 85}, {104, 92}, {105, 80}};
max(stu);
return 0;
}
```
这个程序实现了你要求的功能。在 `main()` 函数中我们定义了一个长度为5的学生对象数组,然后调用函数 `max()`,找出成绩最高的学生的学号。函数 `max()` 通过指针遍历学生数组,找到最高分学生的学号并输出。
希望以上回答能够帮到你,如果你有任何疑问,可以继续问我哦。
相关问题
建立一个对象数组,内放5个学生的学号和成绩,设立一个函数max,用指向对象的指针做函数参数,在max函数种找出5个学生中成绩最高者,并输出其学号。用C++实现
以下是实现代码:
```cpp
#include <iostream>
using namespace std;
class Student {
int id;
float score;
public:
Student(int i, float s) : id(i), score(s) {}
int getId() { return id; }
float getScore() { return score; }
};
void max(Student *arr[], int size) {
int maxIndex = 0;
for (int i = 1; i < size; i++) {
if (arr[i]->getScore() > arr[maxIndex]->getScore()) {
maxIndex = i;
}
}
cout << "最高分数的学生学号为:" << arr[maxIndex]->getId() << endl;
}
int main() {
Student s1(1001, 89.5);
Student s2(1002, 78.5);
Student s3(1003, 92.0);
Student s4(1004, 85.5);
Student s5(1005, 91.0);
Student *arr[5] = { &s1, &s2, &s3, &s4, &s5 };
max(arr, 5);
return 0;
}
```
这里创建了一个 `Student` 类,包含学生的学号和成绩属性,然后在 `main` 函数中创建了 5 个学生对象,并将它们的指针存储在一个指针数组 `arr` 中。最后调用 `max` 函数,使用指向对象的指针作为参数,在其中遍历整个数组,找到成绩最高的学生,并输出其学号。
建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数max,用指向对象的指针作函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号。
以下是代码实现:
```C++
#include <iostream>
using namespace std;
class Student {
public:
int id; // 学号
float score; // 成绩
};
void max(Student* students) {
float max_score = students[0].score; // 设初始的最高成绩为第一个学生的成绩
int max_index = 0; // 最高成绩所在学生在数组中的下标
for (int i = 1; i < 5; i++) {
if (students[i].score > max_score) {
max_score = students[i].score;
max_index = i;
}
}
cout << "学号为 " << students[max_index].id << " 的学生成绩最高,成绩为 " << max_score << endl;
}
int main() {
Student students[5] = {{520, 89}, {521, 78}, {522, 92}, {523, 86}, {524, 95}};
max(students);
return 0;
}
```
上述代码创建了一个名为 Student 的类,用来存储学号和成绩,然后创建了一个 max 函数,它的参数是一个指向 Student 对象的指针。在 max 函数中使用了一个 for 循环,找出数组中成绩最高的学生,在函数结束时输出该学生的学号和成绩。最后在 main 函数中创建了一个包含 5 个学生成绩数据的 Student 对象数组,并将其传递给 max 函数。