6-11 定义有静态成员的C++学生类Student

本程序中学生Student类中有学号 number,姓名 name,成绩 score 等数据成员,另外有静态变量:学生对象个数 count 和总分sum。静态成员函数average( )用来计算学生的平均分。

Student类构造函数的原型如下:

Student(int number1, String name1, float score1);

裁判测试程序样例:

/* 请在这里填写答案 */


int main( )
{ 
//    Student::init( );
    Student stu1(1,"Bill",87); 
    stu1.print( );

    Student stu2(2,"Adam",91);
    stu2.print( );

    Student stu3(3,"David",96);
    stu3.print( );

    Student::average( ); //静态成员函数的调用    

    return 0;
}

输出样例:

在这里给出相应的输出。例如:

number: 1 name: Bill score: 87 count: 1
number: 2 name: Adam score: 91 count: 2
number: 3 name: David score: 96 count: 3
sum is 274
count is 3
average is 91.3333

结尾无空行

参考代码:

#include<iostream>
#include <string>
#include<iomanip>//使用setprecision方法用来控制小数点在iomanip头文件下 
using namespace std; 

class Student{
	public:
		int number;
		string name;
		float score;
		//声明构造函数
		Student(int number1, string name1, float score1);
		//声明普通的输出函数 
		void print(); 
		static double count,sum;
		static float average();

};
//初始化静态成员变量
double Student::count = 0.0;
double Student::sum = 0;
//定义构造函数 
Student::Student(int number1, string name1, float score1){
	number = number1;
	name = name1;
	score = score1;	
}
//定义静态成员函数
float Student::average(){
	float a;
	a = sum / count;
	cout<<"sum is "<<sum<<endl;
	cout<<"count is "<<count<<endl;
	cout<<"average is "<<setprecision(6)<<a;
} 
//定义普通的成员函数 
void Student::print(){
	count++;
	cout<<"number: "<<number<<" name: "<<name<<" score: "<<score<<" count: "<<count<<endl;
	sum = sum + score;
} 

int main()
{ 
//    Student::init( );
    Student stu1(1,"Bill",87); 
    stu1.print( );

    Student stu2(2,"Adam",91);
    stu2.print( );

    Student stu3(3,"David",96);
    stu3.print( );

    Student::average(); //静态成员函数的调用    

    return 0;
}

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值