编写一个程序,已有若干学生的数据,包括学号、姓名、成绩,要求输出这些学生的数据并计算出学生人数和平均成绩(要求将学生人数和总成绩用静态数据成员表示)
时间: 2024-01-05 14:02:25 浏览: 52
这是一个编程问题,我可以提供帮助。以下是一段示例代码,可以输出学生的数据、计算学生人数和平均成绩:
```C++
#include <iostream>
#include <vector>
using namespace std;
class Student {
public:
int id;
string name;
double score;
static int count;
static double total_score;
Student(int i, string n, double s) {
id = i;
name = n;
score = s;
count++;
total_score += s;
}
void print() {
cout << id << "\t" << name << "\t" << score << endl;
}
static double average_score() {
return total_score / count;
}
};
int Student::count = 0;
double Student::total_score = 0;
int main() {
vector<Student> students;
students.push_back(Student(1, "Alice", 90));
students.push_back(Student(2, "Bob", 85));
students.push_back(Student(3, "Charlie", 92));
students.push_back(Student(4, "David", 87));
cout << "id\tname\tscore" << endl;
for (auto student : students) {
student.print();
}
cout << "count:\t" << Student::count << endl;
cout << "average score:\t" << Student::average_score() << endl;
return 0;
}
```
该程序使用类 `Student` 存储学生的数据,包括学号、姓名和成绩,使用静态数据成员 `count` 和 `total_score` 分别计算学生人数和总成绩。在 `main()` 函数中,创建了一个包含若干个学生数据的 `students` 向量,并依次输出每个学生的数据、学生人数和平均成绩。