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
  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. }


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部