[英]My if/else doesn't work correct
我正在嘗試解決一項重要的任務。 我發現王只能移動,如果它的坐標-1 <= x1-x2 and y1-y2 <= 1
。 我的代碼是:
x1 = int(input()) #cuurent x-position
y1 = int(input()) #current y-position
x2 = int(input()) #estimated x-position
y2 = int(input()) #estimated y-position
if -1 <= x1-x2 and y1-y2 <= 1: #king can move to the x2-y2 from x1-y1
print('YES')
else: #king can't move to the x2-y2 from x1-y1
print('NO')
我正常工作與所有的“YES”舉動我能找到,但它不與一些“NO”的動作,如工作:
x1 = 4,y1 = 4,x2 = 2,y2 = 6或x1 = 4,y1 = 4,x2 = 4,y2 = 6
。 我也不知道為什么,因為:4-4 = 0,但是4-6 = -2和-2小於-1。
如果坐標之間的絕對差小於或等於1,則國王可以移動。
因此,寫:
if abs(x1-x2) <= 1 and abs(y1-y2) <= 1: #king can move to the x2-y2 from x1-y1
print('YES')
else: #king can't move to the x2-y2 from x1-y1
print('NO')
這是因為您要移動的坐標可能比要移動的坐標大/小,但是您知道它們之間的差異最多為1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.