编写STL程序,从文本文件中读取分数,然后输出平均分及最高和最低分
时间: 2024-03-13 16:44:08 浏览: 18
好的,我可以为您提供一个基于STL的C++程序,实现从文本文件中读取分数,然后输出平均分及最高和最低分。
以下是程序代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> scores;
string filename = "scores.txt";
// 读取文件中的分数
ifstream infile(filename);
if (!infile.is_open()) {
cout << "无法打开文件 " << filename << endl;
return 1;
}
int score;
while (infile >> score) {
scores.push_back(score);
}
infile.close();
// 计算平均分
int sum = 0;
for (const auto& score : scores) {
sum += score;
}
double average = static_cast<double>(sum) / scores.size();
// 查找最高分和最低分
auto minmax = minmax_element(scores.begin(), scores.end());
int min_score = *minmax.first;
int max_score = *minmax.second;
// 输出平均分及最高和最低分
cout << "平均分:" << average << endl;
cout << "最高分:" << max_score << endl;
cout << "最低分:" << min_score << endl;
return 0;
}
```
以上程序首先通过一个 vector 存储分数。然后,使用 ifstream 从文件中读取分数,并将每个分数添加到 vector 中。接下来,计算平均分,使用 minmax_element 查找最高分和最低分。最后,输出平均分及最高和最低分。
请注意,程序中的文件名和路径可能需要根据实际情况进行修改。