#include<iostream>
using namespace std;
class Score
{
public:
Score()
{
times = 2;
cout << "Score construction1 called" << endl;
}
Score(int times1)
{
times = times1;
cout << "Score construction2 called" << endl;
}
~Score()
{
cout << "Score destruction called" << endl;
}
string name[2];
void InputCoord()
{
for (int i = 0; i < times; i++)
{
cout << "please enter the student's name:";
cin >> name[i];
cout << "please input floatA:" << endl;
cin >> Coord[i][0];
cout << "please input floatB:" << endl;
cin >> Coord[i][1];
cout << "please input floatC:" << endl;
cin >> Coord[i][2];
}
}
void ShowCoord()
{
for (int i = 0; i < times; i++)
{
cout << "name:" << name[i] << endl;
cout << "科目A:" << Coord[i][0] << endl;
cout << "科目B:" << Coord[i][1] << endl;
cout << "科目C:" << Coord[i][2] << endl;
}
}
void ShowAvgCoord()
{
float avgx = 0;
float avgy = 0;
float avgz = 0;
for (int i = 0; i < times; i++)
{
avgx = avgx + Coord[i][0];
avgy = avgy + Coord[i][1];
avgz = avgz + Coord[i][2];
}
avgx = avgx / times;
avgy = avgy / times;
avgz = avgz / times;
cout << "A 平均成绩:" << avgx << endl;
cout << "B 平均成绩:" << avgy << endl;
cout << "C 平均成绩:" << avgz << endl;
}
void ShowSorting()
{
for (int n = 0; n < 3; n++)
{
if (n == 0)
{
cout << "课程A成绩排序:" << endl;
}
if (n == 1)
{
cout << "课程B成绩排序:" << endl;
}
if (n == 2)
{
cout << "课程C成绩排序:" << endl;
}
for (int i = 0; i < times; i++)
{
//float a[100] = {};
float a = 0;
for (int j = i + 1; j < times; j++)
{
if (Coord[i][n] < Coord[j][n])
a = Coord[i][n];
Coord[i][n] = Coord[j][n];
Coord[j][n] = a;
}
}
for (int a = 0; a < times; a++)
cout << "成绩排名" << Coord[a][n] << endl;
}
}
private:
float Coord[100][3];
int times;
};
int main()
{
Score x;
x.InputCoord();
x.ShowCoord();
x.ShowAvgCoord();
x.ShowSorting();
return 0;
}
心得体会:
本次实验继上次继续,上次实验学习了构造函数和析构函数,并进行了一个简单例子的实验与分析。本次实验更近一步,要求创建Score类,来达成一系列要求。本次实验遇到的问题如下:
函数超出堆栈上限,初次定义成了float Coord[100][100],导致超出堆栈报错警告;
没有用循环输出科目排序,导致只有第一组数据没有剩下的组;
本次实验运用的是冒泡法排序,用两个for循环来进行排序,不停的将最大值赋值给该组的第一个数,最后达成排序目的。通过这次实验,让我对C++类的了解更加深厚了,加深了我对各类方法的认识。