7-1 优异生查询(类和对象) (15 分)
题目: 编程实现查找优异生的功能——用户输入多个学生的成绩,输出总分最高的学生姓名和各科成绩
要求: 设计一个学生类(Student),包括
1)属性:姓名(name),数学成绩(mscore),语文成绩(cscore),英语成绩(escore);
2)方法:
构造方法,来构造每个具体的学生对象
计算总成绩方法getSum(self),返回三个成绩的和
获得优异生姓名,数学成绩,语文成绩,英语成绩的方法getBest(self),返回4个结果内容(优异生姓名,数学成绩,语文成绩,英语成绩)
输入格式:
通过4行输入:
第一行输入多个学生姓名,以空格分隔
第二行输入多个数学成绩,以空格分隔
第三行输入多个语文成绩,以空格分隔
第四行输入多个英语成绩,以空格分隔
注意:学生姓名个数要和成绩个数保持一致
输出格式:
在一行中,输出总分最高的学生及其各科科目成绩,以空格分隔。
输入样例:
在这里给出一组输入。例如:
Jack Tom Jim
95 84 32
90 75 45
85 90 67
输出样例:
在这里给出相应的输出。例如:
Jack 95 90 85
参考答案(本人自写):
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Students
{
public:
Students(int numos);
~Students();
string* name;
int* mscore, * cscore, * escore,*sum,count;
void getdata(vector<string> list);
void getBest();
};
Students::Students(int numos)
{
count = numos;
name = new string[numos];
mscore = new int[numos];
cscore = new int[numos];
escore = new int[numos];
sum = new int[numos];
}
Students::~Students()
{
}
void Students::getdata(vector<string> list)
{
for (int i = 0; i < count; i++) cin >> mscore[i];
for (int i = 0; i < count; i++) cin >> cscore[i];
for (int i = 0; i < count; i++) cin >> escore[i];
for (int i = 0; i < count; i++) name[i] = list[i];
}
void Students::getBest()
{
int best = 0;
for (int i = 0; i < count; i++) sum[i] = mscore[i] + cscore[i] + escore[i];
for (int i = 0; i < count; i++)
{
if (sum[best] < sum[i]) best = i;
}
cout << name[best] << ' ' << mscore[best] << ' ' << cscore[best] << ' ' << escore[best] << endl;
}
int main()
{
string currline;
getline(cin, currline);
vector<string> list;
if (currline.size() == 0)return 0;
list.push_back("");
int count = 0;
for (auto it : currline)
if (it == ' ')
{
list.push_back("");
count++;
}
else list[count].push_back(it);
Students stud(count+1);
stud.getdata(list);
stud.getBest();
return 0;
}