【C++ | PTA】计算全班学生C++课程的总成绩和平均成绩

题目要求

定义一个类Student,记录学生C++课程的成绩。要求使用静态数据成员或静态成员函数计算全班学生C++课程的总成绩和平均成绩。

输入格式:
输入5个不超过100的正整数,作为C++成绩。

输出格式:
在第一行中输出成绩的和,第二行输出平均成绩。

输入样例:
90 80 70 60 50

输出样例:
350
70

方法1

#include<bits/stdc++.h>
using namespace std;
class Student{
    protected:
    int studentscore;
    static int sum;
    static double avg;
    public:
    Student(){};
    Student(int a):studentscore(a){
        sum+=a;
        avg=sum/5;
    };
    void disp(){
        cout<<sum<<endl;
        cout<<avg;
    }
};
int Student::sum=0;
double Student::avg=0;
int main(){
    int score;
    Student *p;
    int count=0;
    for(int i=0;i<5;i++){
        cin>>score;
        p=new Student(score);
    }
    p->disp();
    //system("pause");
    return 0;
}

方法2

//未使用静态数据成员,但仍能编译通过
#include <iostream>
using namespace std;

class Student {
private:
    int Score[5];
public:
    Student(int score[]) {
        for (int i = 0; i < 5; i++) {
            Score[i] = score[i];
        }   
    }
    void sum() {
        int Sum = 0;
        for (int i = 0; i < 5; i++) {
            Sum += Score[i];
        }       
        cout << Sum << endl;
    }
    void average() {
        double Average = 0.0;
        int Sum = 0; // 新增一个变量保存成绩总和
        for (int i = 0; i < 5; i++) {
            Sum += Score[i];
        }       
        Average = static_cast<double>(Sum) / 5; // 将 Sum 转换为 double 类型进行除法运算
        //计算平均值之前使用 static_cast<double> 强制将其转换为 double 类型,避免计算结果丢失精度
        cout << Average << endl;
    }
};

int main() {
    int b[5];
    for (int j = 0; j < 5; j++) {
        cin >> b[j];    
    }
    Student S(b);   
    S.sum();
    S.average();
    return 0;
}
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秋说

感谢打赏,祝你平安喜乐。

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

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

打赏作者

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

抵扣说明:

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

余额充值