/* 创建一个矩形类,矩形的边平行于坐标轴。矩形的属性用其左下角坐标、长度和宽度描述。 (1) 从键盘输入两个矩形参数(注意输入提示信息),创建两个矩形对象, 判断两个矩形是否相交?求出相交部分的面积。 (2) 从键盘再输入或随机产生3个矩形对象,对输入的所有5个矩形按面积由小到大排序, 然后依次显示各个矩形的左下角坐标、长、宽、面积。 */
时间: 2024-03-02 14:50:44 浏览: 21
好的,我明白了您的问题。下面是我的回答:
(1)请看下面的代码,其中包含了创建矩形类、判断两个矩形是否相交、求相交部分面积的方法。
```python
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def is_intersect(self, other):
if self.x + self.width <= other.x or self.x >= other.x + other.width:
return False
if self.y + self.height <= other.y or self.y >= other.y + other.height:
return False
return True
def intersect_area(self, other):
if not self.is_intersect(other):
return 0
x1 = max(self.x, other.x)
y1 = max(self.y, other.y)
x2 = min(self.x + self.width, other.x + other.width)
y2 = min(self.y + self.height, other.y + other.height)
return (x2 - x1) * (y2 - y1)
# 从键盘输入两个矩形参数
print("请输入第一个矩形的左下角坐标、长度和宽度:")
x1, y1, w1, h1 = map(int, input().split())
rect1 = Rectangle(x1, y1, w1, h1)
print("请输入第二个矩形的左下角坐标、长度和宽度:")
x2, y2, w2, h2 = map(int, input().split())
rect2 = Rectangle(x2, y2, w2, h2)
# 判断两个矩形是否相交
if rect1.is_intersect(rect2):
# 求相交部分的面积
area = rect1.intersect_area(rect2)
print("两个矩形相交,相交部分的面积为:", area)
else:
print("两个矩形不相交")
```
(2)请看下面的代码,其中包含了随机产生矩形对象、按面积排序、输出每个矩形属性的方法。
```python
import random
# 随机产生一个矩形对象
def generate_random_rectangle():
x = random.randint(0, 10)
y = random.randint(0, 10)
width = random.randint(1, 10)
height = random.randint(1, 10)
return Rectangle(x, y, width, height)
# 从键盘输入或随机产生3个矩形对象
rectangles = []
print("请输入或随机产生3个矩形对象:")
for i in range(3):
print("请输入第", i+1, "个矩形的左下角坐标、长度和宽度:")
x, y, w, h = map(int, input().split())
rectangles.append(Rectangle(x, y, w, h))
for i in range(2):
rectangles.append(generate_random_rectangle())
# 按面积排序
rectangles.sort(key=lambda x: x.width * x.height)
# 输出每个矩形属性
for i, rect in enumerate(rectangles):
print("第", i+1, "个矩形的左下角坐标为:({},{}),长度为{},宽度为{},面积为{}".format(rect.x, rect.y, rect.width, rect.height, rect.width * rect.height))
```