【问题标题】:How do I find which of 2 values are closer to a given number in python?如何在python中找到2个值中的哪一个更接近给定数字?
【发布时间】:2021-11-08 07:12:05
【问题描述】:

我有 2 个变量,value1 和 value2。我想通过 if 语句查看哪些值更接近数字 21。所以在伪代码中,

If value1 is closer to 21:
    Event1
elif value2 is closer to 21:
    Event2
else:
    Event3

【问题讨论】:

  • 提示:可以使用abs()绝对值函数。
  • 想一想在没有计算机的情况下如何解决它。然后将其放入代码中。
  • 想一想你将如何用数学术语来表达这一点。数学上“更接近一个数字”是什么意思?

标签: python if-statement variables integer


【解决方案1】:
def foo(number,val1,val2):
   if abs(number-val1) < abs(number-val2):
      event1()
   elif abs(number-val1)>abs(number-val2):
      event2()
   else:
      event3()

【讨论】:

    【解决方案2】:

    您可以使用绝对值函数,看看 21 和值之间哪个差值更大:

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

    输出:

    value2 is closer
    

    想想你平时会怎么做。你会发现这两个值之间的正差,看看哪个更小!

    【讨论】:

      【解决方案3】:

      我做了这个例子来检查哪个数字更接近:

      #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}')
          
      

      【讨论】:

        猜你喜欢
        • 2016-08-05
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 2014-07-29
        • 2013-09-12
        • 2019-06-22
        • 1970-01-01
        • 2018-08-12
        相关资源
        最近更新 更多