用C++代码写出学生数据由学号、姓名、班级、三门课(数学、英语、计算机)的成绩和平均成绩构成。实现功能为对学生数据排序,分别按平均成绩和计算机成绩的降序
时间: 2024-09-15 21:11:27 浏览: 44
在C++中,你可以创建一个名为`Student`的结构体来表示学生的信息,并包含必要的成员变量。为了方便排序,我们可以将学生的数据存储在一个动态数组(vector)中,然后定义两个函数,一个用于计算平均成绩,另一个用于对数据进行排序。
首先,定义一个`Student`结构体:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Student {
int id;
std::string name;
std::string class_name;
double math_score, english_score, computer_score;
double average_score;
// 构造函数
Student(int id, std::string name, std::string class_name,
double math, double english, double comp)
: id(id), name(name), class_name(class_name),
math_score(math), english_score(english), computer_score(comp) {
calculate_average();
}
// 计算平均成绩
void calculate_average() {
average_score = (math_score + english_score + computer_score) / 3.0;
}
};
// 按平均成绩降序排序
bool compareByAverage(const Student& a, const Student& b) {
return a.average_score > b.average_score;
}
// 按计算机成绩降序排序
bool compareByComputer(const Student& a, const Student& b) {
return a.computer_score > b.computer_score;
}
```
接下来,你可以定义一个`sortStudents`函数来实现排序:
```cpp
void sortStudents(std::vector<Student>& students, bool byAverage) {
if (byAverage) {
std::sort(students.begin(), students.end(), compareByAverage);
std::cout << "Sorted by average score in descending order:\n";
} else {
std::sort(students.begin(), students.end(), compareByComputer);
std::cout << "Sorted by computer score in descending order:\n";
}
for (const auto& student : students) {
std::cout << "ID: " << student.id << ", Name: " << student.name
<< ", Class: " << student.class_name << ", Math: "
<< student.math_score << ", English: " << student.english_score
<< ", Computer: " << student.computer_score << ", Average: "
<< student.average_score << "\n";
}
}
```
现在,你可以创建一些`Student`对象并调用`sortStudents`函数进行排序:
```cpp
int main() {
std::vector<Student> students = { /* 初始化学生数据 */ };
// 排序示例
sortStudents(students, true); // 按平均分排序
sortStudents(students, false); // 按计算机成绩排序
return 0;
}
```
阅读全文