编写程序,输入三角形的三边长,求三角形的面积(海伦公式,开方运算)。
时间: 2024-09-27 19:13:46 浏览: 53
要使用海伦公式计算三角形的面积,给定三条边长a、b和c,你可以按照以下步骤进行:
1. 首先,检查输入的边长是否能构成有效的三角形(任意两边之和大于第三边)。
2. 计算半周长s,其中s = (a + b + c) / 2。
3. 使用海伦公式计算面积A,该公式为 A = sqrt(s * (s - a) * (s - b) * (s - c)),这里sqrt表示开平方根。
以下是用Python实现的示例代码:
```python
import math
def is_valid_triangle(a, b, c):
return a + b > c and a + c > b and b + c > a
def triangle_area(a, b, c):
if not is_valid_triangle(a, b, c):
print("Invalid triangle! The sum of any two sides must be greater than the third side.")
return None
else:
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
return area
# 用户输入三角形的三边长
side_a = float(input("Enter length of side a: "))
side_b = float(input("Enter length of side b: "))
side_c = float(input("Enter length of side c: "))
area = triangle_area(side_a, side_b, side_c)
if area is not None:
print(f"The area of the triangle is {area}.")
```
阅读全文