Python判断点是否在矩形内练习

Python判断点是否在矩形内练习

君若
5年前发布 /正在检测是否收录...

题目

代码

# @Time:    2021/10/15 13:21
# @Auth:    君若(QQ1813774883)

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return "点Point的坐标为({},{})".format(self.x, self.y)


class Rectangle:
    def __init__(self, top_left_x, top_left_y, bottom_right_x, bottom_right_y):
        self.top_left_x = top_left_x
        self.top_left_y = top_left_y
        self.bottom_right_x = bottom_right_x
        self.bottom_right_y = bottom_right_y
        self.chang = 0
        self.kuan = 0

    def __str__(self):
        return "矩形Rectangle的左上角坐标为({},{})右下角坐标为({},{})".format(self.top_left_x, self.top_left_y, self.bottom_right_x,
                                                               self.bottom_right_y)

    def is_hefa(self):
        self.chang = round(self.bottom_right_x - self.top_left_x, 2)
        self.kuan = round(self.top_left_y - self.bottom_right_y, 2)

        if self.chang <= 0 or self.kuan <= 0:  # 矩形左上角和右下角(x1,y2)和(x2,y2) 应该满足 x1<x2   y1>y2 ,才是合法的。
            return 0
        else:
            return 1

    def get_area(self):
        return "矩形:\n 长:{}\n 宽:{}\n 面积:{}".format(self.chang, self.kuan, self.chang * self.kuan)

    def is_inside(self, point):
        if self.top_left_x < point.x < self.bottom_right_x and self.top_left_y > point.y > self.bottom_right_y:
            return "点在矩形内"
        else:
            return "点不在矩形内"


point = Point(2, 3)
rectangle = Rectangle(1, 4, 4, 1)

print(point)
print(rectangle)

if rectangle.is_hefa() == 0:
    print("矩形数据不合法;")
else:
    print(rectangle.get_area())
    print(rectangle.is_inside(point))
© 版权声明
THE END
喜欢就支持一下吧
点赞 0 分享 赞赏
评论 共1条
OωO
取消
  1. 头像
    君若呀
     · 
    回复

    滴!学生卡!打卡时间:下午9:14:57,请上车的乘客系好安全带~