用c++实现编写一个计算三角形面积的函数,函数的参数为三角形三边边长a、b、c,用Heron公式计算,其中包含不是三角形的异常处理
时间: 2024-04-10 21:34:02 浏览: 48
当输入的边长无法构成三角形时,我们可以通过判断三边是否满足三角形不等式来进行异常处理。根据三角形不等式,任意两边之和大于第三边。如果不满足这个条件,我们可以抛出一个异常来处理。
以下是用C++实现计算三角形面积的函数,并包含了异常处理的示例代码:
```cpp
#include <iostream>
#include <cmath>
#include <stdexcept>
double calculateTriangleArea(double a, double b, double c) {
if (a <= 0 || b <= 0 || c <= 0) {
throw std::invalid_argument("边长必须大于零!");
}
if (a + b <= c || a + c <= b || b + c <= a) {
throw std::invalid_argument("无法构成三角形!");
}
double s = (a + b + c) / 2;
double area = std::sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
int main() {
double a, b, c;
std::cout << "请输入三角形的三边边长: ";
std::cin >> a >> b >> c;
try {
double area = calculateTriangleArea(a, b, c);
std::cout << "三角形的面积为: " << area << std::endl;
} catch (const std::exception& e) {
std::cout << "错误: " << e.what() << std::endl;
}
return 0;
}
```
在上述代码中,我们首先判断边长是否大于零,如果有任何一个边长小于等于零,则抛出 `std::invalid_argument` 异常,并显示相应的错误信息。然后,我们根据三边是否满足三角形不等式进行判断,如果不满足,则同样抛出 `std::invalid_argument` 异常,并显示相应的错误信息。如果边长满足条件,我们使用Heron公式计算三角形的面积,并将其返回。
在 `main` 函数中,我们从用户获取三角形的三边边长,并调用 `calculateTriangleArea` 函数计算面积。如果出现异常,我们使用 `try-catch` 块捕获并打印错误信息。
希望这个示例能够满足您的需求!如果还有其他问题,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)