有五名选手 选手 A B C D E ,
10个评委分别对每一名选手进行打分,
去掉一个最高分,去掉一个最低分,取平均分。
采用C++实现,评委打分采用随机数。生成60-100的随机整数
/*
2022.03.16
*/
// 3.4.1 案例描述
//
/*
有五名选手 选手 A B C D E ,
10个评委分别对每一名选手进行打分,
去掉一个最高分,去掉一个最低分,取平均分
*/
// 3.4.2 实现步骤
// 1、创建五名选手,放到 vector 容器
// 2、遍历vector容器,取出来每一个选手,执行for循环,可以把10个选手打存到deque容器中
// 3、sort算法对 deque 容器中的分数排序,去除掉最高分和最低分
// 4、deque容器遍历一遍,累加总分
// 5、获取平均分
#include<iostream>
#include<string>
#include<vector>
#include<deque>
#include<algorithm>
#include<ctime>
using namespace std;
// 选手类
class Person
{
public:
Person(string name, int score)
{
this->m_Name = name;
this->m_Score = score;
}
string m_Name; //姓名
int m_Score;//平均分
};
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);
}
}
void printVector(const vector<Person> &d) //为了防止 函数内部 有些 误操作 修改掉容器数据
{
for (vector<Person> ::const_iterator it = d.begin(); it != d.end(); it++)
{
cout << "姓名:" << (*it).m_Name << "\t" << "分数" << (*it).m_Score << endl ;
}
cout << endl;
}
void setScore(vector<Person> &d)
{
for (vector<Person> ::iterator it = d.begin(); it != d.end(); it++)
{
//将评委的分数放进deque 容器中
deque<int> d;
for (int i = 0; i < 10; i++)
{
int score = rand() % 41 + 60;//rand() % 40 0-40
d.push_back(score);
}
//cout << "选手:" << it->m_Name << "打分:" << endl;
cout << it->m_Name << "打分:" << endl;
for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
{
cout << *dit <<"\t";
}
cout << endl;
//排顺序操作
sort(d.begin(), d.end());
//去除最高 最低
d.pop_back();
d.pop_front();
//获取 平均分
int sum = 0;
for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++)
{
sum += *dit;//累加
}
int average = sum / d.size();//d.size()=8
// 赋值回去
it->m_Score = average;
}
}
void showScore(vector <Person> &v)
{
for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名:" << it->m_Name << endl << "平均分" << it->m_Score << endl;
}
}
int main()
{
//创建随机数种子
srand((unsigned int)time(NULL));
// 1、创建5名选手
vector<Person> v; //存放选手容器
creatPerson(v);
printVector(v);
// 2、给5名选手打分
setScore(v);
// 3、显示最后的得分
showScore(v);
//string str;
//string str1 = "我爱你";
//string str2 = "永远";
//str = str1 + str2;
//cout << "str= " << str << endl;
system("pause");
return 0;
}