4-0. Compile, execute, and test the programs in this chapter.分模块实现各部分功能,初步了解组织大型程序设计方法
//median.h 求中值
#ifndef median_H
#define median_H
#include <vector>
double median(std::vector<double>);
#endif
//median.cpp
#include <algorithm>
#include <vector>
#include <stdexcept>
using namespace std;
double median(vector<double> vec)
{
typedef vector<double>::size_type vec_sz;
vec_sz size=vec.size();
if(size==0)
throw domain_error ("median of an empty vector");
sort(vec.begin(),vec.end());
vec_sz mid=size/2;
return size%2==0?(vec[mid-1]+vec[mid])/2:vec[mid];
}
//Student_info.h
#ifndef Student_info_H
#define Student_info_H
#include <iostream>
#include <string>
#include <vector>
struct Student_info
{
std::string name;
double midterm,fin;
std::vector<double> homework;
};
//for the names' sort(s1,s2,compare)
bool compare(const Student_info& x,const Student_info& y);
//read the students' info
std::istream& read(std::istream& is,Student_info& s);
//read the homework scores
std::istream& read_hw(std::istream& is,std::vector<double>& hw);
#endif
//grade.h
#ifndef grade_H
#define grade_H
#include <vector>
#include "Student_info.h"
double grade(double midterm,double fin,double homework);
double grade(double midterm,double fin,const std::vector<double>& hw);
double grade(const Student_info& s);
#endif
//grade.cpp
#include <stdexcept>
#include <vector>
#include "grade.h"
#include "median.h"
#include "Student_info.h"
using namespace std;
double grade(double midterm,double fin,double homework)
{
return 0.2*midterm+0.4*fin+0.4*homework;
}
double grade(double midterm,double fin,const vector<double>& hw)
{
return grade(midterm,fin,median(hw));
}
double grade(const Student_info& s)
{
return grade(s.midterm,s.fin,s.homework);
}
//Student_info.cpp
#include "Student_info.h"
using namespace std;
bool compare(const Student_info &x,const Student_info &y)
{
return x.name<y.name;
}
istream& read(istream& is,Student_info& s)
{
cout<<"input name,midterm,fin:";
is>>s.name>>s.midterm>>s.fin;
cout<<endl<<"homework score:";
read_hw(is,s.homework);
return is;
}
istream& read_hw(istream& is,vector<double>& hw)
{
if(is)
{
hw.clear();
double x;
while(is>>x)
hw.push_back(x);
is.clear();
}
return is;
}
//main.cpp
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <string>
#i