输入三角形的三边用海伦公式求他们的面积Python
时间: 2024-10-22 22:26:37 浏览: 12
海伦公式可以用来计算任意三角形的面积,给定三边长a、b和c。首先需要验证这是否能构成一个有效的三角形(两边之和大于第三边),然后按照以下步骤计算:
1. 计算半周长(p):\( p = \frac{a + b + c}{2} \)
2. 应用海伦公式求面积(A):\( A = \sqrt{p \times (p - a) \times (p - b) \times (p - c)} \)
以下是用Python实现的函数:
```python
import math
def triangle_area(a, b, c):
# 检查输入是否能构成有效三角形
if a + b > c and a + c > b and b + c > a:
p = (a + b + c) / 2
area = math.sqrt(p * (p - a) * (p - b) * (p - c))
return area
else:
raise ValueError("Invalid input for a triangle. The sum of any two sides must be greater than the third side.")
# 示例使用
try:
a = float(input("Enter the length of side a: "))
b = float(input("Enter the length of side b: "))
c = float(input("Enter the length of side c: "))
area = triangle_area(a, b, c)
print(f"The area of the triangle is {area:.2f}")
except ValueError as e:
print(e)
```
阅读全文