使用c++语言写出程序通过定义静态成员函数对初始化的对象数组实现输入需求前面多少名学生的平均成绩
时间: 2024-02-19 10:57:31 浏览: 28
好的,以下是用C++语言编写的程序,通过定义静态成员函数对初始化的对象数组实现输入需求前面多少名学生的平均成绩:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
class Student {
private:
int score;
public:
static double avgScore(Student* arr, int n) {
sort(arr, arr + n, [](const Student& a, const Student& b) {
return a.score > b.score;
});
double sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i].score;
}
return sum / n;
}
void setScore(int score) {
this->score = score;
}
};
int main() {
const int N = 5;
Student students[N];
for (int i = 0; i < N; i++) {
int score;
cout << "请输入第" << i + 1 << "个学生的成绩:";
cin >> score;
students[i].setScore(score);
}
int num;
cout << "请输入需要计算平均成绩的前几名学生:";
cin >> num;
double avg = Student::avgScore(students, num);
cout << "前" << num << "名学生的平均成绩为:" << avg << endl;
return 0;
}
```
程序中定义了一个`Student`类,其中私有变量`score`表示学生的成绩。接下来定义了一个静态成员函数`avgScore`,该函数接收一个`Student`类型的对象数组和一个整数`n`,表示需要计算前n名学生的平均成绩。在该函数中,首先使用`sort`函数对对象数组进行降序排序,然后计算前n名学生的成绩总和,并返回平均成绩。
在主函数中,首先创建一个对象数组`students`,并通过循环输入每个学生的成绩。然后输入需要计算平均成绩的前几名学生的数量`num`,并调用`Student::avgScore`函数计算平均成绩。最后输出计算结果。
注意:为了避免重复输入,以上程序中仅输入了五个学生的成绩,如需计算更多学生的平均成绩,可修改常量`N`的值。
相关推荐
![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)