6、学生数组排序
问题描述 :
输入3个学生的姓名和英语、数学成绩,需要求每个学生的总成绩并对3个学生按总成绩降序输出,请编写一个类student,实现该功能。
student类的数据成员包括(但不限于)name(姓名,类型为string)、math(数学)、english(英语)。要求用成员函数实现以下功能:
1、使用构造函数给各属性赋初值
2、调用实例方法计算学生总成绩
3、其它必要的功能
另设计一个函数对学生按总成绩降序排列,并在main函数中输出学生信息。
main函数的实现参考如下代码,请设计student类和sortStudent函数。
main函数中声明了一个数组,包含三个对象,然后输入必要信息,给三个对象赋值并计算总成绩,之后对数组排序并按总成绩降序输出学生姓名及其成绩。
对于两个总成绩相同的学生,排序后不改变他们原来的顺序。
int main()
{
student s[3],temp;
string sName;//或char sName[20];
int sMath, sEnglish;
int i;
for(i=0; i<3; i )
{
cin>>sName>>sMath>>sEnglish;
s[i]=student(sName, sMath, sEnglish);
s[i].calcTotal();
}
sortStudent(s, 3);
for(i=0;i<3;i )
{
cout<<s[i].getName()<<" "<<s[i].getMath()<<" "<<s[i].getEnglish()<<" "<<s[i].getTotal()<<endl;
}
return 0;
}
输入说明 :
输入三行,表示三个学生的信息,每一行包括学生姓名、数学成绩、英语成绩,中间以空格分隔。
成绩为0到100之间的整数。
输出说明 :
输出三行,按总成绩降序输出学生姓名及其数学成绩、英语成绩、总成绩。
如果有两个学生总成绩相同,那么原来排在前的学生先输出。
输入范例 :
John 80 90
Kevy 85 90
Lucy 90 80
输出范例 :
Kevy 85 90 175
John 80 90 170
Lucy 90 80 170
解题代码:
#include<iostream>#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<string>#include<map>#include<algorithm>#include<set>#include<vector>#include<queue>using namespace std;class student {public: string name; int math; int english; int all; student(string s,int x,int y); student(void); void calcTotal(); int getMath(); int getEnglish(); int getTotal(); string getName();};student::student(void){ ;}void student::calcTotal(){ all = english math; return ;}student::student(string s, int x, int y){ name = s; math = x; english = y;}int student::getMath(){ return math;}int student::getEnglish(){ return english;}int student::getTotal(){ return all;}string student::getName(){ return name;}void sortStudent(student a[],int n){ if (a[0].all < a[1].all) swap(a[0], a[1]); if (a[0].all < a[2].all) swap(a[0], a[2]); if (a[1].all < a[2].all) swap(a[1], a[2]); return ;}int main(){ student s[3], temp; string sName;//或char sName[20]; int sMath, sEnglish; int i; for (i = 0; i < 3; i ) { cin >> sName >> sMath >> sEnglish; s[i] = student(sName, sMath, sEnglish); s[i].calcTotal(); } sortStudent(s, 3); for (i = 0; i < 3; i ) { cout << s[i].getName() << " " << s[i].getMath() << " " << s[i].getEnglish() << " " << s[i].getTotal() << endl; } return 0;}