完善代码:import math class Triangle: def __init__(self, a, b, c): self.__a = a self.__b = b self.__c = c def get_area(self): h = (self.__a+self.__b+self.__c)/2 s = math.sqrt(h*(h-self.__a)*(h-self.__b)*(h-self.__c)) print(f'三角形的面积:{s}') tri = Triangle(3, 4, 5)
时间: 2023-12-31 08:06:27 浏览: 113
代码已经很完整了,只需要添加一行代码来调用 `get_area()` 方法即可计算三角形的面积,如下所示:
```
tri.get_area()
```
完整代码如下:
```python
import math
class Triangle:
def __init__(self, a, b, c):
self.__a = a
self.__b = b
self.__c = c
def get_area(self):
h = (self.__a+self.__b+self.__c)/2
s = math.sqrt(h*(h-self.__a)*(h-self.__b)*(h-self.__c))
print(f'三角形的面积:{s}')
tri = Triangle(3, 4, 5)
tri.get_area()
```
输出结果为:
```
三角形的面积:6.0
```
相关问题
import math class Graphic: def __init__(self,name): self.name = name def cal_square(self): pass class Triangle(Graphic): def __init__(self,name,height,border): super().__init__(name) self.height = height self.border = border def cal_square(self): square = 1/2 * self.height * self.border print(f"{self.name}的面积是{square:.2f}") class Circle(Graphic): def __init__(self,name,radius): super().__init__(name) self.radius = radius def cal_square(self): square = math.pi * pow(self.radius,2) print(f"{self.name}的面积是{square:.3f}") t1 = Triangle("三角形",6,8) t1.cal_square() c1 = Circle("圆",3) c1.cal_square()给每段代码加上注释
# 导入 math 模块
import math
# 定义图形类
class Graphic:
def __init__(self, name):
self.name = name
# 定义计算面积的方法,需要在子类中重写
def cal_square(self):
pass
# 定义三角形类,继承自图形类
class Triangle(Graphic):
def __init__(self, name, height, border):
super().__init__(name)
self.height = height
self.border = border
# 重写父类的计算面积方法
def cal_square(self):
square = 1/2 * self.height * self.border
print(f"{self.name}的面积是{square:.2f}")
# 定义圆形类,继承自图形类
class Circle(Graphic):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
# 重写父类的计算面积方法
def cal_square(self):
square = math.pi * pow(self.radius, 2)
print(f"{self.name}的面积是{square:.3f}")
# 创建三角形对象并调用计算面积方法
t1 = Triangle("三角形", 6, 8)
t1.cal_square()
# 创建圆形对象并调用计算面积方法
c1 = Circle("圆", 3)
c1.cal_square()
import math class Triangle: def __init__(self, side1=1.0, side2=1.0, side3=1.0): if self.is_valid_triangle(side1, side2, side3): self.side1 = side1 self.side2 = side2 self.side3 = side3 else:
It seems like the code you provided is incomplete. Can you please provide the rest of the code or let me know what your question is regarding the code?
阅读全文