问题描述:用C++实现程序,获取用户输入成绩,输入999结束,求平均成绩、未及格人数。
最近在巩固基础的过程中,帮大一的童靴解了道题,记录一下,便于查询、回顾,同时方便有需要的学习。
// Score.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vecScore; //未指定从用户输入的长度,采用Vector, 动态存储
int MaxScore = 0;
int score = 0;
int Count = 0;
int Sum = 0;
int Average = 0;
cout << "请输入分数最值:";
cin >> MaxScore;
cout << "请输入不大于分数最值的统计分数, 输入999结束:" << endl;
while(1)
{
cin >> score;
if (score == 999) //一般以输入某个数作为结束标志的话,当为该值时直接break.
{
break; //终止整个循环
}
else
{
if (score < (MaxScore + 1)) //score <= MaxScore
{
vecScore.push_back(score); // 压入 score
}
else //score > MaxScore
{
continue; //终止当前循环
}
}
}
vector<int>::iterator itr = vecScore.begin(); //声明指向头和尾的两个迭代器
vector<int>::iterator itrEnd = vecScore.end();
int i = 1;
for (itr; itr != itrEnd; itr++, i++) //遍历Vector
{
Sum += *itr; //计算总成绩
if (*itr < 60) //统计输出未及格人数及序号
{
cout << "序号: " << i << " 分数: "<< *itr << endl;
Count++;
}
}
Average = Sum/vecScore.size(); //平均值计算
cout << "未及格人数: " << Count << endl;
cout << "平均成绩: " << Average << endl;
return 0;
}