C++标准异常处理 三角形面积

2023年5月13日13:09:37
#include<iostream>>
#include<stdexcept>
#include<cmath>
using namespace std;
double area(double a, double b, double c) throw(invalid_argument)
{
	if (a <= 0 || b <= 0 || c <= 0)
		throw invalid_argument("不合法:a<=0 || b<=0 || c<=0");//标准异常类构造时需要传递一个const string&类型参数,表明异常原因
	if (a + b <= c || a + c <= b || b + c <= a)
		throw invalid_argument("不合法:a+b<=c || a+c<=b || b+c<=a");
	double s = (a + b + c) / 2;
	return sqrt(s*(s - a)*(s - b)*(s - c));
}

int main()
{
	double a, b, c;
	while (1)
	{
		cout << "输入三条边长a, b, c= ";
		cin >> a >> b >> c;
		try
		{
			cout<<"s = " << area(a, b, c)<< endl;
		}
		catch (const std::exception& e)
		{
			cout << e.what() << endl;//每一个继承自exception的标准异常都带有what方法,用以读取异常原因
		}
	}
	return 0;
}

C++标准异常处理 三角形面积

  • 作者:祖上是木匠
  • 原文链接:https://blog.csdn.net/weixin_42333471/article/details/88108856
    更新时间:2023年5月13日13:09:37 ,共 565 字。