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