一、实验目的:
(1)掌握类的创建,成员数据和成员函数的构建。
(2)掌握构造函数的重载。
(3)掌握静态成员函数和静态成员函数的使用。
二、实验内容和要求:
(1)按照附件“成绩表.txt”中的内容建立student类,在此类中所有数据定义为私有数据变量。并建立一个student对象数组,用附件中的数据进行初始化。
(2)计算每个学生三门课程的总分和平均成绩,并显示。(通过公有成员函数计算,获取总分和平均成绩);
(3)计算英语、高数、计算机三门课程的平均成绩,并显示。(利用静态成员函数和静态成员变量)
(4)根据平均成绩高低,对所有学生进行排序,并按照从高到低的顺序显示。
附件:
三、源程序代码
#include <iostream>
#include<string.h>
using namespace std;
//定义类
class student
{
public:
student(string n, string xb, string nam, string s, float E, float M, float C, float t, float ave);
float Tsum();
float Taverage();
static void Tsum1();/*定义静态成员函数*/
void print()
{
cout << num << "\t" << departure << "\t" << name << "\t" << sex << "\t" << English << "\t"
<< Math << "\t" << Computer << "\t" << Taverage() << "\t" << Tsum() << endl;
}
float sum;
float average;
/*定义私有数据变量*/
private:
string num;
string departure;
string name;
string sex;
float English;
float Math;
float Computer;
static float sumE;
static float sumM;
static float sumC;
};
float student::sumE = 0, student::sumM = 0, student::sumC = 0;
/*student对象赋值*/
student::student( string n,string xb,string nam,string s, float E, float M, float C, float t=0.0, float ave=0.0)
{
num = n;
departure = xb;
name = nam;
sex = s;
English = E;
Math = M;
Computer = C;
sumE += English;
sumM += Math;
sumC += Computer;
}
/*求总分*/
float student::Tsum()
{
return(English +Math + Computer);
}
/*求平均分*/
float student::Taverage()
{
average=(English + Math + Computer) / 3.0;
return(average);
}
/*求各科平均成绩*/
void student::Tsum1()
{
cout << "英语平均成绩:" << sumE / 5.0 << endl;
cout << "高数平均成绩:" << sumM / 5.0 << endl;
cout << "计算机平均成绩:" << sumC / 5.0 << endl;
}
/*主函数*/
int main()
{
student stu[5] = {
student("02128","机械","杨过","男",64,56,74),
student("02120","计算机","赵海明","男",51,63,84),
student("02119","计算机","张李敏","男",76,87,56),
student("02127","机械","韦小宝","男",75,75,72),
student("02114","外语","姜波","男",79,76,68)
};/*student对象数组初始化*/
cout << "学生成绩表:" <<endl;
cout << "学号\t系别\t姓名\t性别\t英语\t数学\t计算机\t平均分\t总分" << endl;
for (int i = 0; i < 5; i++)
{
stu[i].print();
}
student::Tsum1();
cout << "根据平均成绩高低,对所有学生进行排序后的成绩表为:" << endl;
int j, k;
for (j = 0; j < 5; j++)
{
for (k = 4; k > j; k--)
{
if (stu[k].average > stu[k - 1].average)
{
student temp = stu[k];
stu[k] = stu[k - 1];
stu[k - 1] = temp;
}
}
}/*冒泡算法从高到低排序*/
cout << "学号\t系别\t姓名\t性别\t英语\t数学\t计算机\t平均分\t总分" << endl;
for (int i = 0; i < 5; i++)
{
stu[i].print();
stu[i].Taverage();
stu[i].Tsum();
}
}
四、实验结果