用c++写学生类根据班级平均体重来判断体重水平
时间: 2024-03-24 12:39:52 浏览: 18
好的,以下是一个完整的 C++ 学生类的示例代码,其中增加了根据班级平均体重判断体重水平的功能:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
public:
// 构造函数
Student(string n, int a, string g, float w) {
name = n;
age = a;
gender = g;
weight = w;
}
// 成员函数,用于输出学生的信息
void printInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
cout << "Weight: " << weight << endl;
}
// 静态成员函数,用于计算平均体重
static float calcAvgWeight(vector<Student> students) {
float sum = 0;
int count = 0;
for (auto s : students) {
sum += s.weight;
count++;
}
return sum / count;
}
// 成员函数,用于判断体重水平
void judgeWeightLevel(vector<Student> students) {
float avgWeight = calcAvgWeight(students);
if (weight < avgWeight * 0.8) {
cout << "您的体重偏轻" << endl;
} else if (weight > avgWeight * 1.2) {
cout << "您的体重偏重" << endl;
} else {
cout << "您的体重正常" << endl;
}
}
private:
string name;
int age;
string gender;
float weight;
};
int main() {
// 创建一个名为 Tom、年龄为 18、性别为男、体重为 70kg 的学生对象
Student tom("Tom", 18, "Male", 70);
// 创建一个名为 Alice、年龄为 17、性别为女、体重为 55kg 的学生对象
Student alice("Alice", 17, "Female", 55);
// 创建一个名为 Bob、年龄为 19、性别为男、体重为 75kg 的学生对象
Student bob("Bob", 19, "Male", 75);
// 将学生对象添加到 vector 中
vector<Student> students;
students.push_back(tom);
students.push_back(alice);
students.push_back(bob);
// 输出学生信息
for (auto s : students) {
s.printInfo();
}
// 判断体重水平
for (auto s : students) {
s.judgeWeightLevel(students);
}
return 0;
}
```
在上面的示例代码中,我们在学生类中增加了一个成员函数 `judgeWeightLevel()`,用于根据班级平均体重判断学生的体重水平。在 `judgeWeightLevel()` 函数中,我们通过调用静态成员函数 `calcAvgWeight()` 来计算班级平均体重,然后根据学生的体重与班级平均体重的比较来判断体重水平。在 `main()` 函数中,我们创建了三个学生对象,并将它们添加到一个 vector 中。然后,我们分别调用每个学生对象的 `printInfo()` 和 `judgeWeightLevel()` 函数来输出学生信息和判断体重水平。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)