实验4 构造函数和析构函数
一、实验内容
二、代码
1. .cpp文件
#pragma once
#include "sy4.h"
using namespace std;
class Score {
private:
int num;
int panduan;
string name[100];
float chengji[100][4];
float avg_stu[100];
float avg_xueke[4];
public:
Score();
~Score();
void input();
void show();
};
Score::Score()
{
cout << "学生人数默认为2人,若同意则输入“1”,若要自定义学生个数,请输入“0”" << endl;
cin >> panduan;
if (panduan)
{
num = 2;
}
else
{
cout << "学生人数为:" << endl;
cin >> num;
}
}
Score::~Score()
{
}
void Score::input()
{
int i = 0;
int j = 0;
char z;
float sum_A = 0, sum_B = 0, sum_C = 0;
for (i = 1; i <= num; i++)
{
cout << "请输入学生姓名:" << endl;
cin >> name[i];
float sum_stu = 0;
for (j = 1; j <= 3; j++)
{
z = j + 64;
cout << "请输入科目" << z << "的成绩:";
cin >> chengji[i][j];
sum_stu = sum_stu + chengji[i][j];
}
avg_stu[i] = sum_stu / 3;
sum_A = sum_A + chengji[i][1];
sum_B = sum_B + chengji[i][2];
sum_C = sum_C + chengji[i][3];
}
avg_xueke[1] = sum_A / num;
avg_xueke[2] = sum_B / num;
avg_xueke[3] = sum_C / num;
}
void Score::show()
{
int i = 0, j = 0, k = 0;
char z;
float temp = 0;
string xingming[100];
string xingming_temp;
cout << endl;
for (i = 1; i <= num; i++)
{
cout << name[i];
for (j = 1; j <= 3; j++)
{
z = j+64;
cout <<" " << "科目" << z << "的成绩为:" << chengji[i][j];
}
cout << " 三科平均成绩为:" << avg_stu[i] << endl;
}
cout << endl;
for (j = 1; j <= 3; j++)
{
z = j + 64;
cout << "全体学生科目" << z << "的平均成绩为:" << avg_xueke[j] << endl;
}
cout << endl;
for (j = 1; j <= 3; j++)
{
z = j + 64;
for (i = 1; i <= num; i++)
{
xingming[i] = name[i];
}
cout << "科目" << z << "的成绩按由高到低排序为:" << endl;
for (i = 1; i <= num - 1; i++)
{
for (k = i + 1; k <= num; k++)
{
if (chengji[i][j] > chengji[k][j])
{
temp = chengji[i][j];
chengji[i][j] = chengji[k][j];
chengji[k][j] = temp;
xingming_temp = xingming[i];
xingming[i] = xingming[k];
xingming[k] = xingming_temp;
}
}
}
for (i = num; i >= 1; i--)
{
cout << xingming[i] << " " << chengji[i][j] << endl;
}
}
}
int main()
{
Score stu;
stu.input();
stu.show();
return 0;
}
2. .h文件
#include <iostream>
3.代码运行结果
1.默认人数为2人 2.自定义学生人数
4.问题汇总
1.该问题的原因 出现该问题的原因是本来要求各个同学的三个平均成绩,但是使用的变量是用来存储全体成员每科平均成绩的,故当学生人数超过该变量数组的大小时会造成内存越界。 2.如此可以正确求出各科的总成绩 如此不可以 因为若放在循环中,则重复循环计算了三次,且在第一次由于还未输入科目B和科目C的成绩,此时的chengji[i][2]和chengji[i][3]是随机数。 3.在对成绩进行排序时,当成绩顺序发生改变时,要想该成绩所对应的名字一起改变位置,并且不能对下面成绩顺序造成影响,需要先把原先输入的名字顺序保存到另一个变量。
for (j = 1; j <= 3; j++)
{
z = j + 64;
for (i = 1; i <= num; i++)
{
xingming[i] = name[i];
}
cout << "科目" << z << "的成绩按由高到低排序为:" << endl;
for (i = 1; i <= num - 1; i++)
{
for (k = i + 1; k <= num; k++)
{
if (chengji[i][j] > chengji[k][j])
{
temp = chengji[i][j];
chengji[i][j] = chengji[k][j];
chengji[k][j] = temp;
xingming_temp = xingming[i];
xingming[i] = xingming[k];
xingming[k] = xingming_temp;
}
}
}
for (i = num; i >= 1; i--)
{
cout << xingming[i] << " " << chengji[i][j] << endl;
}
}
4.题目要求是科目A,B,C,而在数组运算中,我们使用的是1,2,3代表,故在输出时通过改变为输出ASCLL码来显示科目A,B,C。
char z;
for (j = 1; j <= 3; j++)
{
z = j + 64;
cout << "全体学生科目" << z << "的平均成绩为:" << avg_xueke[j] << endl;
}
5.其他的排序方法
排序算法
|