python设计代码能够计算键盘输入三条边的三角形的面积。其中,对输入的数据使用异常进行约束,假如输入的数据类型错误则进行“类型错误”的异常处理。假如输入的三条边不能够满足三角形的组成,则抛出自定义的异常类并进行处理。当输入数据都正确时,使用面向对象的编程计算三角形的面积。
时间: 2024-05-10 09:15:25 浏览: 100
好的,以下是代码实现:
```python
class Triangle:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def get_area(self):
p = (self.a + self.b + self.c) / 2
area = (p * (p - self.a) * (p - self.b) * (p - self.c)) ** 0.5
return area
class TriangleError(Exception):
def __init__(self, message):
self.message = message
try:
a = float(input("请输入第一条边长:"))
b = float(input("请输入第二条边长:"))
c = float(input("请输入第三条边长:"))
if a <= 0 or b <= 0 or c <= 0:
raise TriangleError("边长必须大于0!")
if a + b <= c or a + c <= b or b + c <= a:
raise TriangleError("无法构成三角形!")
except ValueError:
print("类型错误!")
except TriangleError as e:
print(e.message)
else:
t = Triangle(a, b, c)
print(f"三角形的面积为:{t.get_area():.2f}")
```
代码中我们定义了一个`Triangle`类来计算三角形的面积,其构造函数接收三条边的长度,`get_area`方法用海伦公式计算面积。我们还定义了一个`TriangleError`异常类来处理输入数据不符合条件的情况。在使用`input`函数获取用户输入时,我们使用了`float`函数将输入转换为浮点数类型,如果转换失败则抛出`ValueError`异常,如果输入的边长不满足构成三角形的条件,就抛出自定义的`TriangleError`异常。如果输入数据符合要求,则创建`Triangle`对象并调用`get_area`方法计算面积并输出。
阅读全文
相关推荐
















