编写一个程序,己有若干学生的数据,包括学号、姓名、成绩,要求输出这些学生的数据并计算出学生人数 和平均成绩(要求将学生人数和总成绩用静态数据成员表示)
时间: 2024-01-06 17:06:27 浏览: 27
这是一个编程问题,我可以回答。您可以使用以下示例代码:
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
static int count; // 静态数据成员,表示学生人数
static int totalScore; // 静态数据成员,表示总成绩
int id;
string name;
int score;
Student(int id, string name, int score) {
this->id = id;
this->name = name;
this->score = score;
count++;
totalScore += score;
}
// 输出学生数据
void print() {
cout << "学号: " << id << " 姓名: " << name << " 成绩: " << score << endl;
}
// 计算平均成绩
static float avgScore() {
return totalScore / (float)count;
}
};
int Student::count = 0;
int Student::totalScore = 0;
int main() {
Student s1(1, "张三", 90);
Student s2(2, "李四", 85);
Student s3(3, "王五", 92);
cout << "学生数据如下:" << endl;
s1.print();
s2.print();
s3.print();
cout << "学生人数: " << Student::count << endl;
cout << "平均成绩: " << Student::avgScore() << endl;
return 0;
}