成绩统计
问题
成绩统计。
用户输入一批0到100分之间的考试成绩,程序给出总的成绩数目和平均成绩,并输出最高成绩和次高成绩。编程要求 :在提示信息score:后面,用户输入一个整数分数,在输入一批分数后,通过输入负数表示输入结束。
程序的输出结果有两种形式:
①如果程序运行过程中,输入了2个及以上规定值域内的有效成绩,输出时:先以total=A,avarage=B的形式输出成绩个数和平均分数,再换行以first=X,second=Y形式输出成绩最高、次高的两个成绩;
②如果程序运行过程中,只输入了1个有效成绩,则输出的第2行只有first=X;
③如果程序运行过程中,自始至终没有输入规定值域内的有效成绩,则只输出:no valid scores。
注意:
①程序显示score:等待用户输入成绩,用户按Enter后,再次显示score:等待用户输入下个成绩;
②当用户在score:后输入的成绩大于100,程序忽略不计;
③当用户在score:后输入的成绩小于0时,程序输出结果后结束;
④除平均成绩保留2位小数外,其余显示出的数值均为整数。
代码
#include <iomanip>
#include <vector>
#include <algorithm>
#include "iostream"
#define ISINT(A) (double(int(A)) == A)
using namespace std;
int main() {
vector<int> scores;
while (true) {
cout << "score:";
int score;
cin >> score;
if (score > 100) continue;
else if (score < 0) break;
else {
scores.push_back(score);
}
}
if (scores.empty()) {
cout << "no valid scores" << endl;
return 0;
}
int total = scores.size();
double sum = 0;
vector<int>::iterator it;
for (it = scores.begin(); it != scores.end(); it++) {
sum += *it;
}
double average = sum / total;
std::sort(scores.begin(), scores.end(), [](int a, int b) { return a > b; });
cout << "total=" << total << ",";
cout << "average=" << fixed << setprecision(2) << average << endl;
int first = scores[0];
if (total == 1) {
cout << "first=" << first << endl;
} else {
int second = scores[1];
cout << "first=" << first << "," << "second=" << second << endl;
}
// for (it = scores.begin(); it != scores.end(); it++) {
// cout << *it << " ";
// }
// cout << endl;
return 0;
}