编写一个函数 area_trangle(a, b, c),其中 a, b, c 是三角形的三条边,要求输入三条边求三角形的面积。
时间: 2024-04-29 18:25:57 浏览: 17
好的,这是一个计算三角形面积的函数,可以使用海伦公式来计算,代码如下:
```python
import math
def area_triangle(a, b, c):
# 计算半周长
s = (a + b + c) / 2
# 计算面积
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
return area
```
你可以把三角形的三条边 a, b, c 传入函数 area_triangle(a, b, c) 中,函数会返回这个三角形的面积。
相关问题
编写一个函数 area_trangle(a, b, c),其中 a, b, c 是三角形的三条 #边,要求输入三条边求三角形的面积。
边长,函数返回三角形的面积。
思路:根据海龙公式,可以计算出三角形的半周长,然后套用面积公式求解。
代码如下:
```
def area_triangle(a, b, c):
s = (a + b + c) / 2 # 计算半周长
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 # 计算面积,使用 ** 表示的是次方运算
return area
```
注意,此函数只能计算三角形的面积,如果输入的三条边不能构成三角形,则会出现错误。
创建一个Shape抽象类,它带有一个area()方法,利用继承产生子类三角形类Trangle类,圆Circle类,矩形Rectangle类, 分别实现计算面积的方法。在测试类中创建圆Circle类对象c,矩形Rectangle类对象r,计算相应图形的面积。
下面是实现代码:
```python
# 创建抽象类 Shape
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
# 创建子类 Triangle
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
# 创建子类 Circle
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# 创建子类 Rectangle
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# 测试类
if __name__ == '__main__':
c = Circle(3) # 创建圆对象
r = Rectangle(2, 4) # 创建矩形对象
# 输出各个图形的面积
print("圆的面积为:", c.area())
print("矩形的面积为:", r.area())
# 创建三角形对象
t = Triangle(3, 4)
print("三角形的面积为:", t.area())
```
输出结果:
```
圆的面积为: 28.26
矩形的面积为: 8
三角形的面积为: 6.0
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![class](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)