【问题标题】:Python 3.X | Determining if a coordinate lies inside a rectanglePython 3.X |确定坐标是否位于矩形内
【发布时间】:2021-05-17 11:29:07
【问题描述】:

目标

我正在编写一个程序,提示用户输入矩形的两个对角:(x1, y1) 和 (x2, y2)。假设矩形的边平行于 x 和 y 轴。如果用户的 (x1, y1) 和 (x2, y2) 坐标创建矩形失败,则打印如下语句:

您输入了两个未能创建矩形的点。退出程序。

如果用户输入适当的坐标来创建一个矩形,程序会提示用户输入第三个点的坐标(x,y)。

程序根据点 (x, y) 是否在矩形内打印 true 或 false。如果该点位于矩形之上或之外,则程序应打印 false。

示例交互

输入 x1: 1

输入 y1: 1

输入 x2: 1

输入 y2: 5

您输入了两个未能创建矩形的点。退出程序。

输入 x1: 0

输入 y1: 0

输入 x2: 3.5

输入 y2:3.5

输入 x: 1.3

输入y:3.5

错误

输入 x1: 4

输入 y1: 4

输入 x2: 0

输入 y2: 0

输入 x: 2

输入y:2

是的

我的代码

# Prompt the user to input (x1, y1), (x2, y2), and (x, y)
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))

# If (x1, y1) and (x2, y2) do not form a rectangle, print the following statement and exit the program
if (x1 == x2 and y1 < y2):
    print("You have entered two points that failed to create a rectangle. Exiting the program")

# Else, prompt the user to enter the (x, y) coordinates
else:
    x = float(input("Enter x: "))
    y = float(input("Enter y: "))
    
    # Print if the (x, y) coordinates are inside the rectangle (true), or on or outside it (false)
    result = (x > x1 and x < x2 and y > y1 and y < y2)
    print(result)

问题

虽然程序工作,但它不正确且与我输入的 (x1, y1)、(x2, y2) 和 (x, y) 坐标不一致。例如,如果我在下面输入以下坐标,我会收到 false 而不是 true。问题是 (x, y) 坐标确实位于矩形内。

我认为我的代码逻辑不正确,尤其是 result 变量。我在网上浏览了关于不同 if-else 语句和逻辑的各种解决方案;但是,我无法弄清楚。我试图通过翻转标志来弄乱逻辑。

我愿意就我所缺少的内容以及如何改进我的代码提供反馈。谢谢。

Enter x1: 4

Enter y1: 4

Enter x2: 0

Enter y2: 0

Enter x: 2

Enter y: 2

**False**

【问题讨论】:

  • 确保x_min &lt; x &lt; x_maxy_min &lt; y &lt; y_max,其中x_min = min(x1, x2)x_max=max(x1, x2) 和y 相同。
  • 条件(x1 == x2 and y1 &lt; y2) 似乎不正确。应该是(x1 == x2 or y1 == y2)
  • @Epsi95 应该是或不是 :)
  • 之后需要确定(xmin, xmax), (ymin, yman),之后就是简单的边界框检查
  • 正确@Divyessh

标签: python python-3.x


【解决方案1】:

你可以这样做:

result = (((x2 > x > x1) or (x1 > x > x2)) and ((y2 > y > y1) or (y1 > y > y2)))

同样对于 if else 部分,将其更改为:

if (x1 == x2 or y1 == y2):
    print("You have entered two points that failed to create a rectangle. Exiting the program")

【讨论】:

  • 谢谢!我根据您的建议更正了我的代码,它解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多