C++/PTA 计算全班学生C++课程的总成绩和平均成绩
题目要求
定义一个类Student,记录学生C++课程的成绩。要求使用静态数据成员或静态成员函数计算全班学生C++课程的总成绩和平均成绩。
输入格式:
输入5个不超过100的正整数,作为C++成绩。
输出格式:
在第一行中输出成绩的和,第二行输出平均成绩。
输入样例:
90 80 70 60 50
输出样例:
350
70
method 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;
}
在 Student 类中,使用了关键字 static 声明了两个静态成员变量 sum 和 avg
。
在 Student 类的构造函数中,当每次创建一个新的 Student 对象时,将该对象的分数值累加到 sum 变量中,从而统计所有学生的总分。然后通过更新 avg 变量
,计算出平均分数。
在 main() 函数中,创建了指向 Student 对象的指针 p
,并在 for 循环中动态地创建了 5 个 Student 对象。由于 sum 和 avg 是静态成员变量,因此它们的值可以被所有 Student 对象共享和访问,所以每次创建一个新对象时,都会更新它们的值。
最后,通过指针 p 调用 disp() 函数
,输出所有学生的总分和平均分。
method 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;
}
定义 Student
类,该类具有两个成员函数 sum()
和 average()
,分别用于计算5名学生的总分和平均分。
在 main()
函数中,首先定义一个包含5个元素的整型数组 b
,用来存储5门课程的分数数据。然后将 b
数组作为实参传递给 Student
类的构造函数,创建一个名为 S
的 Student
对象。
定义Student
类的构造函数中,将传入的 score
数组赋值到 Score
数组中,从而完成了学生对象的初始化。
sum()
函数使用 for 循环遍历 Score
数组,将其中每个元素累加到 Sum
变量中,最终输出累加结果。average()
函数也通过 for 循环遍历 Score
数组,将其中每个元素累加到 Sum
变量中,然后将 Sum
转换为 double
类型进行除法运算,计算出5位学生的平均分,并输出结果。
总结
本文使用两种方法计算全班学生C++课程的总成绩和平均成绩。
我是秋说,我们下次见。