题目要求
定义一个类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;
}