题目描述
输入多个(不超过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/(count1.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才可能显示输出的结果