- 第二部分
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <stdexcept>
using namespace std;
struct Student_info
{
string name;
double midtern, final;
vector<double> homework;
};
double median(vector<double> vec)
{
typedef vector<double>::size_type vec_sz;//vec_sz局部类型名称,只在该函数有效
vec_sz size = vec.size();
if(size == 0)
throw domain_error("median of an empty vector");
/*关于throw,查看上一篇-异常处理
http://blog.csdn.net/qq_31714485/article/details/77952017
*/
//domain_error异常对象,在<stdexcept>中定义的类型,它会向我们报告,函数参数的取值是函数不能接受的。
sort(vec.begin(), vec.end());
vec_sz mid = size / 2;
return size % 2 == 0 ? (vec[mid] + vec[mid - 1]) / 2 : vec[mid];
}
bool compare(const Student_info& x, const Student_info& y)
{
return x.name < y.name;
}
double grade(double midterm, double final, double homework)
{
return 0.2*midterm + 0.4*final + 0.4*homework;
}
//函数重载,根据函数参数列表,系统自动辨别我们调用的是哪个函数。
double grade(double midterm, double final, const vector<double>& hw)//const vector<double>& hw称为对参数类型为double的向量常量的引用,或者双精度向量常量引用。
{
if (hw.size() == 0)//提供更多的异常提示,以便跟好的了解错误所在.
throw domain_error("student has done no homework");
return grade(midterm, final, median(hw));
}
double grade(const Student_info &s)
{
return grade(s.midtern,s.final,s.homework);
}
//读一个输入流,把homework成绩读进vector<double>类型的向量中.都是引用
istream& read_hw(istream& in, vector<double>& hw)
{
if(in)
{
//清除原先的内容
hw.clear();
//读取
double x;
while (cin>>x)
hw.push_back(x);
//清除流以使输入动作对下一个学生有效
in.clear();
}
return in;
}
istream& read(istream& is, Student_info& s)
{
//读入并存储学生的姓名以及其中、期末考试成绩
is>>s.name>>s.midtern>>s.final;
read_hw(is,s.homework);//读入并存储学生所用家庭作业成绩
return is;
}
int main()
{
vector <Student_info> students;
Student_info record;
string::size_type maxlen = 0;
//读并存储所有记录,然后找出最长的姓名的长度
while(read(cin,record))
{
maxlen = max(maxlen,record.name.size());
students.push_back(record);
};
//按字母顺序排序记录
sort(students.begin(),students.end(),compare);
for(vector<Student_info>::size_type i=0; i!=students.size();++i)
{
//输出姓名,填充姓名以达到maxlen+1的长度
//cout<<setw(maxlen+1)<<students[i].name;
//setw设置输出宽度时,默认为右对齐
//为name填充字符,同时输出name的运算符将把流的宽度重置为0.因此没有必要像使用setprecision时
//记住重置宽度。
cout<<students[i].name<<string(maxlen+1 - students[i].name.size(),' ');
//计算并输出总成绩
try
{
double final_grade = grade(students[i]);
streamsize prec = cout.precision();//设置小数点位数,并保存原来的小数点位数为prec
cout << setprecision(3) <<final_grade << setprecision(prec) << endl;
}
catch (domain_error e)
{
cout <<e.what();
}
cout<<endl;
}
return 0;
}