有5名選手,選手ABCDE,10個評委分別對每一名選手打分,去除一個最高分,去除一個最低分,取平均分。
1、創建五名選手,放到vector中,
2、遍歷vector容器,取出來每一個選手,執行for循環,可以把10個評委打分存到deque容器中
3、sort算法對deque容器中分數排序,pop_back、pop_front去除最高和最低分
4、duque容器遍歷一遍,累加分數,累加分數/d.size()
5、person.score = 平均分
使用STL代碼,實現如下:
#include <iostream>
#include <string>
#include <functional>
#include <stdexcept>
#include <vector>
#include <deque>
#include <algorithm>
#include <ctime>
using namespace std;
/*
有5名選手,選手ABCDE,10個評委分別對每一名選手打分,去除一個最高分,去除一個最低分,取平均分。
//1、創建五名選手,放到vector中,
//2、遍歷vector容器,取出來每一個選手,執行for循環,可以把10個評委打分存到deque容器中
//3、sort算法對deque容器中分數排序,pop_back、pop_front去除最高和最低分
//4、duque容器遍歷一遍,累加分數,累加分數/d.size()
//5、person.score = 平均分
*/
class Person{
public:
Person(string name, int score)
{
this->m_Name = name;
this->m_Score = score;
}
string m_Name;
int m_Score;
};
void createPerson(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 setScore(vector<Person>& v)
{
for (vector<Person>::iterator it = v.begin(); it != v.end();it++)
{
//對5個人進行打分
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 dit = d.begin(); dit != d.end();dit++)
{
sum += *dit;
}
//評價分
int avg = sum / d.size();
it->m_Score = avg;
}
}
void showScore(vector<Person> &v)
{
for (vector<Person>::iterator it = v.begin(); it != v.end();it++)
{
cout << "姓名: " << it->m_Name << ", 最終平均分: " << it->m_Score << endl;
}
}
int main()
{
//設置隨機種子
srand((unsigned int)time(NULL));
//容器存放選手
vector<Person> v;
//創建5名選手
createPerson(v);
//打分
setScore(v);
//展示平均分
showScore(v);
system("pause");
return 0;
}
效果如下:
圖(1) 5個選手的平均分