定义一个类,根据输入点数不同,分别计算三角形和正方形面积和周长。写这个的代码
时间: 2024-05-06 17:21:21 浏览: 57
好的,这是一个可以执行上述操作的 Python 类的代码示例:
```
class Shape:
def __init__(self, n):
self.n = n
def calculate_area(self):
if self.n == 3:
# calculate area of triangle
side_a = float(input("Enter the length of side a: "))
side_b = float(input("Enter the length of side b: "))
side_c = float(input("Enter the length of side c: "))
s = (side_a + side_b + side_c) / 2
area = (s * (s - side_a) * (s - side_b) * (s - side_c)) ** 0.5
print(f"The area of the triangle is {area:.2f} square units.")
elif self.n == 4:
# calculate area of square
side = float(input("Enter the length of a side: "))
area = side ** 2
print(f"The area of the square is {area:.2f} square units.")
else:
print("Invalid input.")
def calculate_perimeter(self):
if self.n == 3:
# calculate perimeter of triangle
side_a = float(input("Enter the length of side a: "))
side_b = float(input("Enter the length of side b: "))
side_c = float(input("Enter the length of side c: "))
perimeter = side_a + side_b + side_c
print(f"The perimeter of the triangle is {perimeter:.2f} units.")
elif self.n == 4:
# calculate perimeter of square
side = float(input("Enter the length of a side: "))
perimeter = 4 * side
print(f"The perimeter of the square is {perimeter:.2f} units.")
else:
print("Invalid input.")
```
要使用这个类,只需要创建一个对象并调用相应的方法即可。例如:
```
my_shape = Shape(3)
my_shape.calculate_area() # prompts user to input side lengths and calculates area of triangle
my_shape.calculate_perimeter() # prompts user to input side lengths and calculates perimeter of triangle
```
如果点数输入错误,类会输出 `"Invalid input."` 。
请问还有什么问题需要我解答吗?
阅读全文