//统计学生平均成绩
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n,int a,int s):num(n),age(a),score(s){}
void total();
static float average();//声明静态成员函数
private:
int num;
int age;
float score;
static float sum;//静态数据成员sum——总分
static int count;//静态数据成员count——计数
};
void Student::total()
{
sum+=score;
count++;
}
float Student::average()//静态成员函数只能使用静态数据成员
{
return(sum/count);
}
float Student::sum=0;//类外静态数据成员初始化
int Student::count=0;
int main()
{
Student stud[3]={ Student(10010,18,79),Student(10011,20,89),Student(10012,19,88)};
int n;
cout<<"please input the number of students:";
cin>>n;//输入需要求的学生数
for(int i=0;i<n;i++)
stud[i].total();
cout<<"the average of score of "<<n<<" students is "<<Student::average()<<endl;//调用静态成员函数
return 0;
}
使用静态成员函数 统计学生成绩
最新推荐文章于 2026-04-01 09:13:06 发布
本文介绍了一个简单的C++程序,用于统计并计算一组学生的平均成绩。通过定义一个Student类,利用静态成员变量记录总分及学生数量,并提供静态成员函数计算平均分。

2825

被折叠的 条评论
为什么被折叠?



