用C++编写一个学生类,要求该类完成如下功能:(1)输出每个学生的姓名、学号、成绩;(2)统计并输出学生的总人数、总成绩、平均成绩、最高成绩、最低成绩。
时间: 2024-12-26 19:28:27 浏览: 6
在C++中,我们可以创建一个名为`Student`的基本类来满足这些需求。首先,我们需要包含必要的头文件,并定义一些私有成员变量存储学生的信息,以及公有成员函数来进行操作。
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int student_id;
double score;
public:
// 构造函数初始化学生信息
Student(string n, int id, double s) : name(n), student_id(id), score(s) {}
// 输出学生的姓名、学号和成绩
void display() {
cout << "姓名: " << name << ", 学号: " << student_id << ", 成绩: " << score << endl;
}
// 统计总人数、总成绩、平均成绩、最高成绩和最低成绩
static int totalStudents;
static double totalScore, averageScore, highestScore, lowestScore;
static void calculateSummary(Student* students, int count) {
totalStudents = count;
totalScore = 0;
for (int i = 0; i < count; ++i) {
totalScore += students[i].score;
}
if (count > 0) {
averageScore = totalScore / count;
highestScore = *max_element(students, students + count, [](const Student& a, const Student& b) { return a.score < b.score; });
lowestScore = *min_element(students, students + count, [](const Student& a, const Student& b) { return a.score > b.score; });
} else {
averageScore = highestScore = lowestScore = 0;
}
}
};
// 初始化静态变量
Student::totalStudents = 0;
Student::totalScore = 0.0;
Student::averageScore = 0.0;
Student::highestScore = 0.0;
Student::lowestScore = numeric_limits<double>::infinity();
// 示例如何使用
int main() {
Student student1("张三", 1, 85);
Student student2("李四", 2, 92);
Student student3("王五", 3, 78);
// 添加更多学生...
Student students[] = {student1, student2, student3};
int numStudents = sizeof(students) / sizeof(students[0]);
// 调用计算函数
Student::calculateSummary(students, numStudents);
// 输出统计结果
cout << "总人数: " << Student::totalStudents << endl;
cout << "总成绩: " << Student::totalScore << endl;
cout << "平均成绩: " << Student::averageScore << endl;
cout << "最高成绩: " << Student::highestScore << endl;
cout << "最低成绩: " << Student::lowestScore << endl;
return 0;
}
```
在这个例子中,我们定义了一个`Student`类,包含了姓名、学号和成绩的属性。`display()`函数用于显示单个学生的信息,而`calculateSummary()`函数则用于统计所有学生的总体数据。注意,这里使用了C++的`std::max_element()`和`std::min_element()`来找到最高分和最低分。
阅读全文