计算三角形面积(异常处理)
问题本身很简单,贴这个代码主要是想强调一下里面涉及到的异常处理
#include<iostream>
#include<cmath>
#include<stdexcept>
using namespace std;
double area(double a, double b, double c) throw (invalid_argument)
{
if (a <= 0 || b <= 0 || c <= 0)
throw invalid_argument("the side length should be positive");
if (a + b <= c || b + c <= a || a + c <= b)
throw invalid_argument("the side length should fit the thriangle inequation");
double s = (a + b + c) / 2;
return sqrt(s*(s - a)*(s - b)*(s - c));
}
int main()
{
double a, b, c;
cout << "please input the side length of thriangle:" << endl;
cin >> a >> b >> c;
try
{
double s=area(a, b, c);
cout << "Area:" << s << endl;
}
catch (exception &e)
{
cout << "Error:" << e.what() << endl; //what()是Exception基类中的一个成员函数,用于返回错误信息
}
return 0;
}