Accelerated C++:通过示例进行编程实践——练习解答(第4章)

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
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值