C++ 学生信息管理系统:设计学生类,计算总分并查询信息
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string id;
string name;
int math;
int physics;
int english;
public:
Student(string id = '', string name = '', int math = 0, int physics = 0, int english = 0) {
this->id = id;
this->name = name;
this->math = math;
this->physics = physics;
this->english = english;
}
~Student() {}
void setInfo(string id, string name, int math, int physics, int english) {
this->id = id;
this->name = name;
this->math = math;
this->physics = physics;
this->english = english;
}
int getTotalScore() {
return math + physics + english;
}
void printInfo() {
cout << 'name: ' << name << endl;
cout << 'ID: ' << id << endl;
cout << 'math scores: ' << math << endl;
cout << 'physics scores: ' << physics << endl;
cout << 'english scores: ' << english << endl;
cout << 'overall scores: ' << getTotalScore() << endl;
}
string getID() {
return id;
}
};
int main() {
Student students[5];
// 输入5个学生的成绩信息
for (int i = 0; i < 5; i++) {
string id, name;
int math, physics, english;
cin >> id >> name >> math >> physics >> english;
students[i].setInfo(id, name, math, physics, english);
}
int maxScore = 0;
for (int i = 0; i < 5; i++) {
int totalScore = students[i].getTotalScore();
if (totalScore > maxScore) {
maxScore = totalScore;
}
}
cout << 'max scores: ' << maxScore << endl;
string queryID;
cin >> queryID;
for (int i = 0; i < 5; i++) {
if (students[i].getID() == queryID) {
students[i].printInfo();
break;
}
}
return 0;
}
在这个程序中,我们定义了一个 Student 类来表示学生。
以下是代码解释:
-
Student类:- 包含私有成员:学号
id、姓名name、数学成绩math、物理成绩physics和英语成绩english。 - 包含公有成员函数:
- 构造函数:初始化学生信息
- 析构函数
setInfo:设置学生信息getTotalScore:计算总成绩printInfo:输出学生所有信息getID:获取学生学号
- 包含私有成员:学号
-
main函数:- 创建一个包含 5 个学生对象的数组
students。 - 通过循环输入 5 个学生的成绩信息,并使用
setInfo函数设置每个学生的信息。 - 计算并输出最高总分。
- 输入要查询的学号
queryID。 - 遍历学生数组,找到对应学号的学生,并使用
printInfo函数输出该学生的全部信息。
- 创建一个包含 5 个学生对象的数组
改进之处:
- 为
Student类的构造函数添加默认参数,使其更加灵活。 - 在代码中添加注释,提高代码可读性。
- 对用户输入进行校验,例如检查学号是否为 11 位数字等,以增强程序的健壮性。
希望这个改进后的代码能够帮助你更好地理解如何使用 C++ 处理学生信息。
原文地址: https://www.cveoy.top/t/topic/bwOl 著作权归作者所有。请勿转载和采集!