C++定义Student类,计算全班总分和平均分

  1. 具体要求如下:
  2. 定义一个Student类,在该类定义中包括一个数据成员score(分
    数)、两个静态数据成员total(总分)和学生人数count;成员函
    数scoretotalcount(floats)用于设置分数、求总分和累计学生人数;
    静态成员函数sum()用于返回总分;静态成员函数average()
    用于求平均值。在main()函数中,输入某班同学的成绩,并调用
    上述函数求全班学生的总分和平均分。
  3. 注意静态变量在类外初始化,如:
  1.         float Student::total = 0;
    1.         int Student::count = 0;
    2. 如下代码实现求班级总分和人数
    3. void Student::scoretotalcount(float s)
    4. {
    5.     score = s;
    6.     total = total + score;
    7.     count++;
    8. }
  2. 具体代码如下:

  3. #include<iostream>
  4. using namespace std;
  5. class Student
  6. {
  7. private:
  8.     float score;
  9.     static float total;
  10.     static int count;
  11. public:
  12.     void scoretotalcount(float s);  //声明scoretotalcount()函数,实现求学生总数,成绩总分
  13.     static float sum();             //声明sum()函数,返回总成绩
  14.     static float average();         //声明average()函数,返回平均数
  15. };
  16. float Student::total = 0;
  17. int Student::count = 0;
  18. void Student::scoretotalcount(float s)
  19. {
  20.     score = s;
  21.     total = total + score;
  22.     count++;
  23. }
  24. float Student::sum()
  25. {
  26.     return total;
  27. }
  28. float Student::average()
  29. {
  30.     return total / count;
  31. }
  32. int main()
  33. {
  34.     Student stu[100];
  35.     int i, n;
  36.     float s;
  37.     cin >> n;
  38.     for (i = 0; i < n; i++)
  39.     {
  40.         cin >> s;
  41.         stu[i].scoretotalcount(s);
  42.     }
  43.     cout << "total=" << Student::sum() << endl;    //调用sum()函数
  44.     cout << "average=" << Student::average() << endl;  //调用average()函数
  45.     return 0;
  46. }
  • 7
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晨露02

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值