要用c++的cincout
时间: 2024-03-09 18:51:21 浏览: 114
好的,以下是使用C++的代码实现:
```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
ifstream fin("scores.txt"); // 打开scores.txt文件
vector<int> scores;
int score;
while (fin >> score) {
scores.push_back(score); // 读入数据
}
fin.close(); // 关闭文件
int score_90_100 = 0, score_80_89 = 0, score_70_79 = 0, score_60_69 = 0, score_below_60 = 0;
for (int i = 0; i < scores.size(); i++) { // 统计各分数段的人数
if (scores[i] >= 90) {
score_90_100++;
} else if (scores[i] >= 80) {
score_80_89++;
} else if (scores[i] >= 70) {
score_70_79++;
} else if (scores[i] >= 60) {
score_60_69++;
} else {
score_below_60++;
}
}
int total_students = scores.size(); // 统计总人数
double average_score = accumulate(scores.begin(), scores.end(), 0.0) / total_students; // 计算平均成绩
int max_score = *max_element(scores.begin(), scores.end()); // 计算最高分
int min_score = *min_element(scores.begin(), scores.end()); // 计算最低分
// 计算各分数段的占比(保留小数点后四位)
double percent_90_100 = round(score_90_100 * 10000.0 / total_students) / 100.0;
double percent_80_89 = round(score_80_89 * 10000.0 / total_students) / 100.0;
double percent_70_79 = round(score_70_79 * 10000.0 / total_students) / 100.0;
double percent_60_69 = round(score_60_69 * 10000.0 / total_students) / 100.0;
double percent_below_60 = round(score_below_60 * 10000.0 / total_students) / 100.0;
ofstream fout("result.txt"); // 打开result.txt文件
fout << "总人数:" << total_students << endl;
fout << fixed << setprecision(2); // 设置小数点后两位
fout << "平均成绩:" << average_score << endl;
fout << "最高分:" << max_score << endl;
fout << "最低分:" << min_score << endl;
fout << "90~100分人数:" << score_90_100 << ",占比:" << percent_90_100 << "%" << endl;
fout << "80~89分人数:" << score_80_89 << ",占比:" << percent_80_89 << "%" << endl;
fout << "70~79分人数:" << score_70_79 << ",占比:" << percent_70_79 << "%" << endl;
fout << "60~69分人数:" << score_60_69 << ",占比:" << percent_60_69 << "%" << endl;
fout << "小于60分人数:" << score_below_60 << ",占比:" << percent_below_60 << "%" << endl;
fout.close(); // 关闭文件
return 0;
}
```
运行完上述代码后,会在当前目录下生成一个result.txt文件,其中包含了统计结果。
阅读全文