C++进阶实例1--评委打分
C++进阶实例1--评委打分
1 #include<iostream> 2 #include<vector> 3 #include<deque> 4 #include<algorithm> 5 #include<string> 6 #include<ctime> 7 using namespace std; 8 9 // 容器实例1-评委打分 10 // 问题描述: 11 // 有5名选手,选手ABCDE,10个评委分别对每一位选手打分; 12 // 去除一个最高分,去除一个最低分,取平均分; 13 // 解决思路: 14 // 1.创建无名选手,放到vector 15 // 2.遍历vector容器,取出每一个选手,执行for循环,可以把10个评分打分存到deque容器中 16 // 3.sort算法对deque容器中分数排序,去除最高分和最低分 17 // 4.deque容器遍历一遍,累加总分 18 // 5.获取平均分 19 // 20 21 22 // 选手类 23 class Person { 24 public: 25 26 Person(string name, int score) { 27 this->m_Name = name; 28 this->m_Score = score; 29 } 30 31 string m_Name; // 姓名 32 int m_Score; // 平均分 33 }; 34 35 36 // 创建选手 37 void createPerson(vector<Person>&v) { 38 string nameSeed = "ABCDE"; 39 for (int i = 0; i < 5; i++) { 40 string name = "选手"; 41 name += nameSeed[i]; 42 43 int score = 0; 44 Person p(name, score); 45 46 // 将创建的person对象,放入到容器中 47 v.push_back(p); 48 } 49 } 50 51 // 为选手打分 52 void setScore(vector<Person>& v) { 53 for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) { 54 55 //将评委的分数 放入的到deque容器中 56 deque<int>d; 57 for (int i = 0; i < 10; i++) { 58 int score = rand() % 41 + 60; // 60~100 59 d.push_back(score); 60 } 61 62 // 测试 63 //cout << "选手:" << it->m_Name << "打分:" << endl; 64 //for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++) { 65 // cout << *dit << " "; 66 //} 67 //cout << endl; 68 69 // 排序 70 sort(d.begin(), d.end()); 71 72 // 去除最高和最低分 73 d.pop_back(); 74 d.pop_front(); 75 76 // 取平均分 77 int sum = 0; 78 for (deque<int>::iterator dit = d.begin(); dit != d.end(); dit++) { 79 sum += *dit; // 累加每个评委的分数 80 } 81 82 int avg = sum / d.size(); 83 84 // 讲平均分 赋值给选手身上 85 it->m_Score = avg; 86 87 } 88 } 89 90 // 显示最后得分 91 void showScore(vector<Person>&v) { 92 93 for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) { 94 cout << "姓名:" << it->m_Name << " 平均分:" << it->m_Score << endl; 95 } 96 97 } 98 99 100 int main() { 101 102 // 随机数种子 103 srand((unsigned int)time(NULL)); 104 105 // 1.创建5名选手 106 vector<Person>v; // 存放选手容器 107 createPerson(v); 108 109 // 测试 110 //for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) { 111 // cout << "姓名:" << (*it).m_Name << " 分数:" << (*it).m_Score << endl; 112 //} 113 114 // 2.给5名选手打分 115 setScore(v); 116 117 // 3.显示最后得分 118 showScore(v); 119 120 121 122 system("pause"); 123 124 return 0; 125 }
浙公网安备 33010602011771号