C++编程案例讲解-评委打分案例

评委打分案例

  • 案例说明

案例说明

有5名选手,10个评委分别对每一名选手打分,去除最高分,去除最低分,取平均分
要求以下步骤:

  1. 创建5名选手,放到vector中
  2. 遍历vector容器,取出来每一位选手,指定for循环,可以把10个评委打分存到deque中
  3. sort算法对deque容器中分数排序,去除最高分和最低分
  4. deque容器中遍历一遍,累加总分
  5. 获取平均分
#include 
#include 
#include 
#include 
#include 
using namespace std;

class Player
{
private:
    string name;
    float score;
public:
    Player(string name)
    {
        this->name = name;
        this->score = 0;
    }
    void printf()
    {
        std::cout << "姓名:" << this->name << "\t最终得分: " << this->score << std::endl;
    }
    void setScore(float score)
    {
        this->score = score;
    }
    string getName()
    {
        return this->name;
    }
};

void simulated_scoring(Player& player)
{
    deque<float> score;
    for (int i = 0; i < 10; i++)
    {
        float so = rand() % 60 + 40;
        std::cout << "第" << i << "位评委给 " << player.getName() << " 打出的分数为:" << so << "分" << std::endl;
        score.push_back(so);
    }
    //排序
    sort(score.begin(), score.end());
    //去掉一个最高分
    score.pop_back();
    //去掉一个最低分
    score.pop_front();

    float sum = 0;
    //求和取平均
    for (deque<float>::iterator it = score.begin(); it != score.end(); it++)
    {
        sum += *it;
    }
    player.setScore(sum / score.size());
}

int main()
{
    srand((unsigned int)time(NULL));
    string name[] = { "张三","李四","王五","赵二","武义" };
    vector<Player> player;
    //初始化5位运动员
    for (int i = 0; i < sizeof(name) / sizeof(name[0]); i++)
    {
        Player pl(name[i]);
        player.push_back(pl);
    }
    
    for (vector<Player>::iterator it = player.begin(); it != player.end(); it++)
    {
        simulated_scoring(*it);
    }
    
    for (vector<Player>::iterator it = player.begin(); it != player.end(); it++)
    {
        (*it).printf();
    }
}

C++编程案例讲解-评委打分案例_第1张图片

你可能感兴趣的:(C++入门与进阶内容专栏,c++,开发语言)