实验目的:
一.观察例程中的函数和析构函数的顺序。
由运行结果可知构造函数和析构函数的运行顺序为:
1.void Inputcoord()
2.void Showcoord()
3.void ShowAvgcoord()
4.析构函数
二.在main函数中加入代码的尝试
加入代码后要求输入的组数变成了5组,结果如上图所示,两个析构函数都是在最后运行的。
代码及结果如下:
#include<iostream>
using namespace std;
class Score {
public:
Score()
{
student_number = 2;
}
Score(int time1 = 0) {
student_number = time1;
}
~Score() {}
void student_name_score() {
for (int i = 0; i < student_number; i++) {
cout << "请输入学生姓名:" << endl;
cin >> name[i];
cout << "请输入科目A的成绩:" << endl;
cin >> score[i][1];
cout << "请输入科目B的成绩:" << endl;
cin >> score[i][2];
cout << "请输入科目C的成绩:" << endl;
cin >> score[i][3];
grades[i] = score[i][1] + score[i][2] + score[i][3];
}
}
void show_score() {
for (int i = 0; i < student_number; i++) {
cout <<"姓名:"<< name[i]<<" " << "科目A的分数为:" << score[i][1] <<" " << "科目B的分数为:" << score[i][2]<< " " << "科目C的分数为:" << score[i][3]<<" " << "平均成绩为:" << grades[i] / 3 << endl;
}
}
void subject_avg_score() {
for (int i = 0; i < student_number; i++) {
avgA = avgA + score[i][1];
}
avgA = avgA / student_number;
cout << "科目A的平均成绩为:" <<avgA << endl;
for (int i = 0; i < student_number; i++) {
avgB = avgB + score[i][2];
}
avgB = avgB / student_number;
cout << "科目B的平均成绩为:" <<avgB << endl;
for (int i = 0; i < student_number; i++) {
avgC = avgC + score[i][3];
}
avgC = avgC / student_number;
cout << "科目C的平均成绩为:" <<avgC << endl;
}
void score_sort() {
float a, b, c, x;
a = avgA;
b = avgB;
c = avgC;
if (a > b) {
x = a;
a = b;
b = x;
}
if (a > c) {
x = a;
a = c;
c = x;
}
if (b > c) {
x = b;
b = c;
c = x;
}
cout << "成绩由高到低为:" << c <<" "<< b <<" " << a << endl;
}
private:
float avgA=0, avgB=0, avgC=0;
int student_number;
float score[100][100];
float grades[100];
string name[100];
};
int main() {
Score L(2);
L.student_name_score();
L.show_score();
L.subject_avg_score();
L.score_sort();
return 0;
}
遇到的问题:
1.在输入名字时出现错误,我用的double改用string可运行。
2.排序方式开始时用的冒泡排序,之后换用为以上的排序方式,可运行。
3.我想用sort函数排序时,结果显示avg定义过多,未解决。