举办歌手大奖赛。设计歌手类,包括:编号、姓名、各评委打分等属性。 要求功能: 可以打印当前最高、最低分选手属性; 打印已出场人数; 可以按照平均分由高到低打印已出场选手属性; 写出main函数中模拟n个选手出场的过程。 要求:使用静态成员。
时间: 2024-05-30 16:16:34 浏览: 31
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Singer {
public:
Singer(int id, string name): id(id), name(name), score(0), count(0) {}
void addScore(double s) {
score += s;
count++;
}
double getAverageScore() const {
return count > 0 ? score / count : 0;
}
int getId() const {
return id;
}
string getName() const {
return name;
}
static Singer* getMaxScoreSinger() {
return max_score_singer;
}
static Singer* getMinScoreSinger() {
return min_score_singer;
}
static void printNumOfSingers() {
cout << "Num of singers: " << singers.size() << endl;
}
static void printSingersByScore() {
vector<Singer*> sorted_singers(singers);
sort(sorted_singers.begin(), sorted_singers.end(), [](Singer* s1, Singer* s2) {
return s1->getAverageScore() > s2->getAverageScore();
});
cout << "Singers by score: " << endl;
for (Singer* s : sorted_singers) {
cout << s->getId() << " " << s->getName() << " " << s->getAverageScore() << endl;
}
}
private:
int id;
string name;
double score;
int count;
static vector<Singer*> singers;
static Singer* max_score_singer;
static Singer* min_score_singer;
};
vector<Singer*> Singer::singers;
Singer* Singer::max_score_singer = nullptr;
Singer* Singer::min_score_singer = nullptr;
int main() {
int n;
cout << "Num of singers: ";
cin >> n;
for (int i = 1; i <= n; i++) {
string name;
cout << "Name of singer " << i << ": ";
cin >> name;
Singer* s = new Singer(i, name);
singers.push_back(s);
}
double score;
for (int i = 0; i < 5; i++) {
cout << "Judge " << i+1 << " score: ";
cin >> score;
for (Singer* s : singers) {
s->addScore(score);
}
}
Singer* max_singer = singers[0];
Singer* min_singer = singers[0];
for (Singer* s : singers) {
if (s->getAverageScore() > max_singer->getAverageScore()) {
max_singer = s;
}
if (s->getAverageScore() < min_singer->getAverageScore()) {
min_singer = s;
}
}
Singer::max_score_singer = max_singer;
Singer::min_score_singer = min_singer;
cout << "Max score singer: " << Singer::getMaxScoreSinger()->getId() << " " << Singer::getMaxScoreSinger()->getName() << " " << Singer::getMaxScoreSinger()->getAverageScore() << endl;
cout << "Min score singer: " << Singer::getMinScoreSinger()->getId() << " " << Singer::getMinScoreSinger()->getName() << " " << Singer::getMinScoreSinger()->getAverageScore() << endl;
Singer::printNumOfSingers();
Singer::printSingersByScore();
for (Singer* s : singers) {
delete s;
}
return 0;
}
阅读全文