编写一个面向对象的程序,实现从键盘输入5个学生的学号、成绩,找出5个学生中成绩最高者并输出其学号和成绩。用c++
时间: 2023-06-19 09:06:04 浏览: 148
以下是一个面向对象的程序,实现从键盘输入5个学生的学号、成绩,找出5个学生中成绩最高者并输出其学号和成绩。
```C++
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string id; // 学生学号
int score; // 学生成绩
public:
void input(); // 输入学生信息
void output(); // 输出学生信息
int getScore(); // 获取学生成绩
};
void Student::input() {
cout << "请输入学生的学号和成绩:" << endl;
cin >> id >> score;
}
void Student::output() {
cout << "学生的学号为:" << id << endl;
cout << "学生的成绩为:" << score << endl;
}
int Student::getScore() {
return score;
}
int main() {
Student students[5];
int maxScore = -1;
int maxIndex = -1;
// 输入5个学生的信息
for (int i = 0; i < 5; i++) {
students[i].input();
}
// 找出成绩最高的学生
for (int i = 0; i < 5; i++) {
if (students[i].getScore() > maxScore) {
maxScore = students[i].getScore();
maxIndex = i;
}
}
// 输出成绩最高的学生的学号和成绩
cout << "成绩最高的学生的学号为:" << students[maxIndex].id << endl;
cout << "成绩最高的学生的成绩为:" << students[maxIndex].getScore() << endl;
return 0;
}
```
上述程序中,我们定义了一个 `Student` 类,其中包含了学生的学号和成绩,并且提供了三个成员函数:`input()` 用于输入学生信息,`output()` 用于输出学生信息,`getScore()` 用于获取学生成绩。
在 `main()` 函数中,我们定义了一个 `Student` 类型的数组 `students`,用于存储5个学生的信息。然后我们通过循环调用 `input()` 函数,输入每个学生的信息。
接下来,我们通过循环调用 `getScore()` 函数,找出成绩最高的学生,记录其在数组中的下标。最后,我们输出成绩最高的学生的学号和成绩。
阅读全文
相关推荐


















