编写一个程序,己有若干学生的数据,包括学号、姓名、成绩,要求输出这些学生的数据并计算出学生人数 和平均成绩(要求将学生人数和总成绩用静态数据成员
时间: 2024-01-06 18:06:04 浏览: 60
好的,以下是一个简单的 C++ 程序,可以实现您的需求:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
int id;
string name;
double score;
static int count;
static double totalScore;
Student(int id, string name, double score) {
this->id = id;
this->name = name;
this->score = score;
count++;
totalScore += score;
}
void print() {
cout << id << "\t" << name << "\t" << score << endl;
}
static void printSummary() {
cout << "Total students: " << count << endl;
cout << "Average score: " << totalScore / count << endl;
}
};
int Student::count = 0;
double Student::totalScore = 0;
int main() {
Student s1(1, "Tom", 80);
Student s2(2, "Jerry", 90);
Student s3(3, "Alice", 85);
cout << "ID\tName\tScore" << endl;
s1.print();
s2.print();
s3.print();
Student::printSummary();
return 0;
}
```
程序中定义了一个 `Student` 类,包含学号、姓名、成绩三个属性,以及两个静态数据成员 `count` 和 `totalScore`,用于记录学生人数和总成绩。
在 `main` 函数中创建了三个学生对象,并逐个输出其数据。最后调用 `Student::printSummary()` 函数输出学生人数和平均成绩。
注意,这里只是一个示例程序,实际应用中需要根据具体需求进行修改。