1. 程式人生 > 其它 >C++進階例項1--評委打分

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 }