【C++ Primer Plus习题】15.3

大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←

问题:

这里是引用

解答:
main.cpp

#include <iostream>
#include <cmath>
#include "exc_mean.h"
using namespace std;

double hmean(double a, double b);
double gmean(double a, double b);

int main()
{
	double x, y, z, m;
	cout << "请输入两个数字: ";
	while (cin >> x >> y)
	{
		try
		{
			z = hmean(x, y);
			m = gmean(x, y);
			cout << x << "和" << y << "的调和平均数为" << z << endl;
			cout << x << "和" << y << "的几何平均数为" << m << endl;
			cout << "输入下一组数据,按q结束:" << endl;
		}
		catch (unexpected_mean& bg)
		{
			if (typeid(bg) == typeid(bad_hmean))
			{
				bad_hmean* ph = dynamic_cast<bad_hmean*>(&bg);
				ph->mesg();
			}
			else if (typeid(bg) == typeid(bad_gmean))
			{
				bad_gmean* ph = dynamic_cast<bad_gmean*>(&bg);
				ph->mesg();
			}
			cout << "Try again!" << endl;
			continue;
		}
		
	}
	cout << "Bye" << endl;

	return 0;
}

double hmean(double a, double b)
{
	if (a == -b)
		throw bad_hmean(a,b);
	return 2.0 * a * b / (a + b);
}
double gmean(double a, double b)
{
	if (a < 0 || b < 0)
		throw bad_gmean(a,b);
	return sqrt(a * b);
}

exc_mean.h

#pragma once
#include <iostream>
#include <stdexcept>
using namespace std;

class unexpected_mean :public logic_error
{
private:
	double v1;
	double v2;
public:
	unexpected_mean(double a=0,double b=0,string s="mean error"):v1(a),v2(b),logic_error(s){}
	virtual void mesg() = 0;
};

class bad_hmean :public unexpected_mean
{
public:
	bad_hmean(double a=0,double b=0,const string s = "HMean") :unexpected_mean(a,b,s) {}
	void mesg() override;
};

class bad_gmean :public unexpected_mean
{
public:
	bad_gmean(double a = 0, double b = 0, const string s = "GMean") :unexpected_mean(a,b,s) {}
	void mesg() override;
};

inline void unexpected_mean::mesg()
{
	cout << v1 << " " << v2 << endl;
}

inline void bad_hmean::mesg()
{
	cout << "bad_HMean() now!" << endl;
	cout << what() << endl;
	cout << "Hmean invalid arguments\n";
	unexpected_mean::mesg();
}

inline void bad_gmean::mesg()
{
	cout << "bad_Gmean() now!" << endl;
	cout << what() << endl;
	cout << "Gmean invalid arguments\n";
	unexpected_mean::mesg();
}


运行结果:
在这里插入图片描述

考查点:

  • 异常
  • dynamic_cast
  • 虚函数
  • 内联函数

注意:

  • 继承类的异常处理
    在这里插入图片描述

2024年9月11日20:37:15

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值