簡體   English   中英

如何在python中找到2個值中的哪一個更接近給定數字?

[英]How do I find which of 2 values are closer to a given number in python?

我有 2 個變量,value1 和 value2。 我想通過 if 語句查看這些值中哪些更接近數字 21。 所以在偽代碼中,

If value1 is closer to 21:
    Event1
elif value2 is closer to 21:
    Event2
else:
    Event3
def foo(number,val1,val2):
   if abs(number-val1) < abs(number-val2):
      event1()
   elif abs(number-val1)>abs(number-val2):
      event2()
   else:
      event3()

您可以使用絕對值函數並查看 21 和這些值之間哪個差異更大:

value1 = 40
value2 = 8

if abs(21 - value1) < abs(21 - value2):
  print('value1 is closer')
else:
  print('value2 is closer')

輸出:

value2 is closer

想想你通常會怎么做。 您會發現兩個值之間的正差異,看看哪個更小!

我做了這個例子來檢查哪個數字更接近:

#Setting variables
val1 = 2
val2 = 1
cond = 21

check1 = val1
check2 = val2

#arrays to save numbers between
arr1 = []
arr2 = []

#Conditioning values

#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)
        arr2.append(check2)
        check2 += 1

result1 = len(arr1)
result2 = len(arr2)
# Checking which value is closer
if(result1 == result2):
    print('Both numbers are equaly closer')

elif(result1 < result2):
    print(f'The number {val1} is closer to {cond}')

else:
    print(f'The number {val2} is closer to {cond}')
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM