本程序中学生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;
}
|