- 具体要求如下:
- 定义一个Student类,在该类定义中包括一个数据成员score(分
数)、两个静态数据成员total(总分)和学生人数count;成员函
数scoretotalcount(floats)用于设置分数、求总分和累计学生人数;
静态成员函数sum()用于返回总分;静态成员函数average()
用于求平均值。在main()函数中,输入某班同学的成绩,并调用
上述函数求全班学生的总分和平均分。 - 注意静态变量在类外初始化,如:
- float Student::total = 0;
- int Student::count = 0;
- 如下代码实现求班级总分和人数
- void Student::scoretotalcount(float s)
- {
- score = s;
- total = total + score;
- count++;
- }
- 具体代码如下:
- #include<iostream>
- using namespace std;
- class Student
- {
- private:
- float score;
- static float total;
- static int count;
- public:
- void scoretotalcount(float s); //声明scoretotalcount()函数,实现求学生总数,成绩总分
- static float sum(); //声明sum()函数,返回总成绩
- static float average(); //声明average()函数,返回平均数
- };
- float Student::total = 0;
- int Student::count = 0;
- void Student::scoretotalcount(float s)
- {
- score = s;
- total = total + score;
- count++;
- }
- float Student::sum()
- {
- return total;
- }
- float Student::average()
- {
- return total / count;
- }
- int main()
- {
- Student stu[100];
- int i, n;
- float s;
- cin >> n;
- for (i = 0; i < n; i++)
- {
- cin >> s;
- stu[i].scoretotalcount(s);
- }
- cout << "total=" << Student::sum() << endl; //调用sum()函数
- cout << "average=" << Student::average() << endl; //调用average()函数
- return 0;
- }