3.4 评委打分案例
3.4.1 案例描述
功能:有五名选手:ABCDE,10个评委分别对每一名选手打分,去除最高分,去除评委中最低分,取平均分。
3.4.2 实现步骤
1.创建5名选手,放到vector中
2.遍历vector容器,取出来每个选手,执行for循环,可以把10个评分打分存到deque容器中。
3.sort算法对deque容器的分数排序,去除最高和最低分。
4.deque容器遍历一遍,累加总分
5.获取平均分
#include <iostream>
using namespace std;
//包含容器的头文件
#include<vector>
#include<deque>
#include<string>
//包含算法头文件
#include<algorithm>
//选手类
class Person
{
public:
string m_Name;
int m_Score;
Person(string name, int score)
{
this->m_Name = name;
this->m_Score = score;
}
};
//创建选手,将选手放入vector容器
void creatPerson(vector<Person> &v)
{
string nameSeed = "ABCDE";
for(int i = 0; i < 5; i++)
{
//选手名称
string name="选手";
name += nameSeed[i];
//选手分数
int score = 0;
//创建选手
Person p(name, score);
//选手放入容器
v.push_back(p);
}
}
//给选手打分,总共10个评委
void setScore(vector<Person>& v)
{
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
//将10个评委的分数放入deque容器
deque<int> d;
for (int i = 0; i < 10; i++)
{
int score = rand()%41+60;//60-100
d.push_back(score);
}
//对分数进行排序
sort(d.begin(), d.end());
//去除最高和最低分
d.pop_back();
d.pop_front();
//获取总分
int sum=0;
for (deque<int>::iterator it = d.begin(); it != d.end(); it++)
{
sum += *it;
}
//获取平均分
int avg = sum / (d.size());
//平均分赋值给人
(*it).m_Score = avg;
}
}
int main()
{
//1.创建5名选手,放入到vector容器中
vector<Person> v;//存放选手容器
creatPerson(v);
/* for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名:" << (*it).m_Name << " 分数:" << (*it).m_Score << endl;
}*/
//2.遍历vector容器,取出来每个选手,执行for循环,可以把10个评分打分存到deque容器中。
//3.sort算法对deque容器的分数排序,去除最高和最低分。
//4.deque容器遍历一遍,累加总分
//5.获取平均分
setScore(v);
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名:" << (*it).m_Name << " 分数:" << (*it).m_Score << endl;
}
system("pause");
system("cls");
}