类与对象6(静态成员:平均分)

匿名 (未验证) 提交于 2019-12-02 23:34:01

题目描述

输入多个(不超过20个)学生的学号与分数,计算所有学生的平均分。

要求:使用类的静态成员来计算。

输入

多个学生的学号与分数。

输出

所有学生的平均分(保留2位小数)。

样例输入 Copy

zhangsan 500
lisi 528
wangwu 546
zhaoliu 512
#include
#include
using namespace std;
class Student
{
private:
char *name; //姓名
int score; //成绩
static int count; //记录对象个数
static int sum; //记录总成绩
public:
Student(char name,int score)
{
this->name=name;
this->score=score;
} //构造函数
int getsum(); //计算总成绩
static double average(); //获取成绩平均值
};
int Student::count=0;
int Student::sum=0;
int Student::getsum()
{
count++;//记录个数
return sum+=score;//求和
}
double Student::average()
{
double x;
x=sum/(count
1.0);//乘以1.0是因为出现小数点
if (count!=0)
cout<<fixed<<setprecision(2)<<(x)<<endl;//在iomanip函数下使用fixed setprecision() 目的是为了精确小数点的个数
else
cout<<count<<endl;
}
int main()
{
int score,count;
char name[20];
while(cin>>name>>score)
{
Student s(name,score);
s.getsum();
}
Student::average();//调用函数时可以使用类名+函数
return 0;
}
在使用while(cin>>name>>score)时,在输出时需要Ctrl+z才可能显示输出的结果

文章来源: https://blog.csdn.net/weixin_43847899/article/details/90289177
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!