设计一个学生类(Student),包含一个根据实际学生人数计算平均分的成员函数。 建立一个对象数组,存放3个学生的数据(学号、成绩),调用该成员函数求这3个学生的平均成绩。
时间: 2023-07-16 19:16:44 浏览: 50
以下是一个可能的实现:
```cpp
#include <iostream>
using namespace std;
class Student {
public:
Student(int id, double score) {
this->id = id;
this->score = score;
}
double getScore() const { return score; }
static double averageScore(Student students[], int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
sum += students[i].getScore();
}
return sum / n;
}
private:
int id;
double score;
};
int main() {
Student students[] = {Student(1, 90), Student(2, 80), Student(3, 85)};
int n = sizeof(students) / sizeof(Student);
double avgScore = Student::averageScore(students, n);
cout << "The average score of " << n << " students is " << avgScore << endl;
return 0;
}
```
在这个实现中,`Student` 类表示学生对象,包含学号和成绩两个成员变量。`averageScore` 是一个静态成员函数,用于计算给定学生数组的平均成绩。在 `main` 函数中,我们创建一个 `Student` 对象数组,然后使用 `averageScore` 函数计算平均分并输出结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)