您的位置:首页 > 编程语言 > C语言/C++

chapter15test3

2015-07-01 15:53 393 查看
mean.h

#include<iostream>

#include<stdexcept>

class base :public std::logic_error

{

private:
double x; double y;

public:
base(double a = 0, double b = 0) :x(a), y(b),logic_error(0){}
double xr(){ return x; }
double yr(){ return y; }

};

class bad_hmean:public base

{

public:
bad_hmean(double a,double b) :base(a,b){}
void what();

};

inline void bad_hmean::what()

{
std::cout << "You can't process Hmean() with x= " << xr() << ",y= " << yr() << std::endl;

}

class bad_gmean :public base

{

public:
bad_gmean(double a = 0, double b = 0) :base(a,b){}
void what();

};

inline void bad_gmean::what()

{
std::cout << "You can't process Gmean() with x= " << xr() << ",y= " << yr() << std::endl;

}

user.cpp

#include<iostream>

#include<cmath>

#include"mean.h"

using namespace std;

double hmean(double a, double b);

double gmean(double a, double b);

int main()

{
double x, y, z;
cout << "Enter two numbaers :\n";
while (cin >> x >> y)
{
try{z = hmean(x, y);
cout << "Hmean(" << x << "," << y << ")=" << z << endl;
cout << "Gmean(" << x << "," << y << ")=" << gmean(x,y) << endl;
}
catch(bad_hmean &h)
{
h.what();
break;
}
catch (bad_gmean &g)
{
g.what();
break;
}
}
cout << "Finished .\n";

}

double hmean(double a, double b)

{
if (a != -b)
return 2.0*a*b / (a + b);
else
throw bad_hmean(a,b);

}

double gmean(double a, double b)

{
if (a > 0 && b > 0)
return sqrt(a*b);
else
throw bad_gmean(a, b);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++