📄 9-4.cpp
字号:
#include<algorithm>
#include<iomanip>
#include<ios>
#include<iostream>
#include<stdexcept>
#include<string>
#include<vector>
class Student_info
{
public:
Student_info(); //construct an empty Student_info object
Student_info(std::istream&); //construct one by read a stream
std::string name() const
{
return n;
}
bool valid() const
{
return !homework.empty();
}
std::istream& read(std::istream&);
double grade() const;
private:
std::string n;
double midterm,final;
std::vector<double> homework;
};
bool compare(const Student_info&,const Student_info&);
int main()
{
Student_info record(std::cin);
if(record.valid())
{
double final_grade=record.grade();
std::streamsize prec=std::cout.precision();
std::cout<<std::setprecision(3)<<final_grade
<<std::setprecision(prec)<<std::endl;
}
return 0;
}
double median(std::vector<double> vec)
{
typedef std::vector<double>::size_type vec_sz;
vec_sz size=vec.size();
if(size==0)
throw std::domain_error("median of an empty vector");
std::sort(vec.begin(),vec.end());
vec_sz mid=size/2;
return size%2==0?(vec[mid]+vec[mid-1])/2:vec[mid];
}
//compute a student's overall grade from midterm and final exam grades
double grade(double midterm,double final,double homework)
{
return 0.2*midterm+0.4*final+0.4*homework;
}
//compute a student's overall grade from minterm and final exam grades
//and vector of homework grades
//this funtion does not copy its argument median does so far
double grade(double midterm,double final,const std::vector<double>& hw)
{
if(hw.size()==0)
throw std::domain_error("student has done no homework");
return grade(midterm,final,median(hw));
}
bool compare(const Student_info& x,const Student_info& y)
{
return x.name()<y.name();
}
//read homework grades from an input stream into a 'vector'
std::istream& read_hw(std::istream& in,std::vector<double>& hw)
{
if(in)
{
//get rid of previous contents
hw.clear();
//read homework grades
double x;
while(in>>x)
hw.push_back(x);
//clear the stream so that input will work for the next student
in.clear();
}
return in;
}
//std::istream& read(std::istream&);
std::istream& Student_info::read(std::istream& in)
{
in>>n>>midterm>>final;
read_hw(in,homework);
return in;
}
//the default constructor
Student_info::Student_info():midterm(0),final(0)
{
}
Student_info::Student_info(std::istream& is)
{
read(is);
}
double Student_info::grade() const
{
return ::grade(midterm,final,homework);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -