数据结构课程设计运动会分数分析代码
时间: 2023-07-11 19:29:21 浏览: 51
好的,以下是一个简单的数据结构课程设计运动会分数分析代码,使用C++语言实现:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Athlete {
string name;
double score;
};
bool cmp(const Athlete &a, const Athlete &b) {
return a.score > b.score;
}
int main() {
ifstream infile("score.txt"); // 从文件中读取成绩
vector<Athlete> athletes;
string name;
double score;
while (infile >> name >> score) {
athletes.push_back({name, score});
}
infile.close();
sort(athletes.begin(), athletes.end(), cmp); // 按分数从高到低排序
int n = athletes.size();
double sum = 0;
for (int i = 0; i < n; i++) {
sum += athletes[i].score;
}
double average = sum / n; // 计算平均分数
cout << "运动会分数分析报告:" << endl;
cout << "---------------------" << endl;
cout << "参赛人数:" << n << endl;
cout << "平均分数:" << average << endl;
cout << "前三名成绩:" << endl;
for (int i = 0; i < 3 && i < n; i++) {
cout << athletes[i].name << ": " << athletes[i].score << endl;
}
return 0;
}
```
以上代码通过打开名为score.txt的文件,依次读取每个运动员的姓名和分数,将其存储在一个名为athletes的向量中。然后,使用STL的sort函数将运动员按照分数从高到低排序,并计算所有分数的平均值。最后输出运动会分数分析报告,包括参赛人数、平均分数以及前三名的成绩和姓名。