计算全班学生c++课程的总成绩和平均成绩,要求使用静态数据成员,输入5个整数作为c++成绩
时间: 2023-06-10 12:07:34 浏览: 107
以下是一个示例代码:
```cpp
#include <iostream>
using namespace std;
class Course {
public:
static int count; // 静态数据成员,记录学生数量
static int total; // 静态数据成员,记录总成绩
Course(int score) {
count++;
total += score;
}
};
int Course::count = 0;
int Course::total = 0;
int main() {
int score;
for (int i = 0; i < 5; i++) {
cin >> score;
Course c(score);
}
cout << "总成绩为:" << Course::total << endl;
cout << "平均成绩为:" << Course::total / Course::count << endl;
return 0;
}
```
程序中定义了一个`Course`类,其中有两个静态数据成员`count`和`total`,分别记录学生数量和总成绩。在`Course`类的构造函数中,每当创建一个对象时,`count`自增1,`total`累加该对象的成绩。在`main`函数中,循环读入5个成绩,并创建`Course`对象,最后输出总成绩和平均成绩,需要使用类名限定静态成员的访问。