C++系统性学习之考试成绩统计
在本篇博客中,我们将学习如何使用C++编写一个程序,根据给定的考试成绩,计算最高分、最低分和平均分。
问题描述
我们的任务是编写一个C++程序,接受用户输入的考试人数和每个学生的得分,然后计算并输出最高分、最低分和平均分。
解决方案
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
// 输入考试人数
int n;
cout << "请输入考试人数: ";
cin >> n;
vector<int> scores;
// 循环读取每个学生的得分,并存储在向量中
for (int i = 0; i < n; ++i) {
int score;
cout << "请输入第 " << i + 1 << " 个学生的得分: ";
cin >> score;
scores.push_back(score);
}
// 计算最高分、最低分和平均分
int maxScore = *max_element(scores.begin(), scores.end());
int minScore = *min_element(scores.begin(), scores.end());
double avgScore = accumulate(scores.begin(), scores.end(), 0.0) / n;
// 输出结果
cout << maxScore << endl;
cout << minScore << endl;
cout << fixed << setprecision(2) << avgScore << endl;
return 0;
}