[英]Python 3.X | Determining if a coordinate lies inside a rectangle
我正在編寫一個程序,提示用戶輸入矩形的兩個對角:(x1,y1)和(x2,y2)。 假設矩形的邊平行於 x 和 y 軸。 如果用戶的 (x1, y1) 和 (x2, y2) 坐標創建矩形失敗,則打印如下語句:
您輸入了兩個未能創建矩形的點。 退出程序。
如果用戶輸入適當的坐標來創建一個矩形,程序會提示用戶輸入第三個點的坐標 (x, y)。
程序根據點 (x, y) 是否在矩形內打印 true 或 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) 坐標確實位於矩形內。
我相信我的代碼邏輯不正確,特別是對於結果變量。 我在網上瀏覽了關於不同 if-else 語句和邏輯的各種解決方案; 但是,我無法弄清楚。 我試圖通過翻轉標志來弄亂邏輯,但無濟於事。
我願意就我所缺少的內容以及如何改進我的代碼提供反饋。 謝謝你。
Enter x1: 4
Enter y1: 4
Enter x2: 0
Enter y2: 0
Enter x: 2
Enter y: 2
**False**
你可以這樣做:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.