我有兩個變數,value1和value2。我想通過if陳述句查看哪個值更接近數字21。所以在偽代碼中,
如果value1 是接近21。
事件1
elif value2 is 更接近21。
事件2
else:
事件3
希望得到任何幫助,謝謝!
uj5u.com熱心網友回復:
你可以使用絕對值函式,看看21和值之間哪個差值更大:
value1 = 40。
value2 = 8
if abs(21 - value1) < abs(21 - value2) 。
print('value1 is closer')
else:
print('value2 is closer')
輸出:
value2 is closer
想想你通常會怎么做。你會找到兩個值之間的正差,然后看看哪個值更小 希望這有幫助
。uj5u.com熱心網友回復:
def foo(number,val1,val2)。
if abs(number-val1) < abs(number-val2)。
事件1()
elif abs(number-val1)>abs(number-val2)。
事件2()
else:
event3()
uj5u.com熱心網友回復:
我做了這個例子來檢查哪個數字更接近,希望它能對你有所幫助
#Setting variables。
val1 = 2
val2 = 1
cond=21
check1 = val1
check2 = val2
#arrays to save numbers between
arr1 = []
arr2 = []
#條件值
#Value 1 check
if(check1 > cond)。
while check1 > cond:
# print(check1).
arr1.append(check1)
check1 -=1
elif(check1 == cond)。
arr1 = [cond]
else:
while check1 < cond:
# print(check1).
arr1.append(check1)
check1 =1
#Value 2 check。
if(check2 > cond)。
while check2 > cond:
# print(check2).
arr2.append(check2)
check2 -=1
elif(check2 == cond)。
arr2 = [cond]
else:
while check2 < cond:
# print(check2)/span>
arr2.append(check2)
check2 =1
result1 = len(arr1)。
result2 = len(arr2)
# 檢查哪一個值更接近。
if(result1 == result2)。
print('Both numbers are equaly closer'/span>)
elif(result1 < result2)。
print(f'The number {val1} is closer to {cond}'/span>)
else:
print(f'The number {val2} is closer to {cond}' /span>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314500.html
標籤:
