【问题标题】:How to round a number to its lowest value using int() in python [duplicate]如何在python中使用int()将数字四舍五入到最小值[重复]
【发布时间】:2021-04-14 03:03:41
【问题描述】:

我想要的是:

if 1700 / 1000 = 1.7 = int(1) # I want this to be True
   lst.append("T")

我原来的代码是:

if 1700 / 1000 == int(1) # This is False and I want it to be True
   lst.append("T")

if 语句为 False,因为答案是 1.7 而不是 1。我希望这是 True。所以我希望 1.7 使用 int 向下舍入到 1,以便 if 语句为 True。

【问题讨论】:

  • 欢迎来到 StackOverflow。一些有帮助的文档:docs.python.org/3.7/library/…。请注意,“除法”具有三种风格。您正在寻找最后一个(执行 floordiv)。

标签: python rounding truncate


【解决方案1】:

你要么需要把 int 放在另一边:

if int(1700 / 1000) == 1
   lst.append("T")

即在比较之前将 1700/1000 舍入为整数, 或者使用//,即整数除法,舍弃小数部分:

if 1700 // 1000 == 1
   lst.append("T")

【讨论】:

    【解决方案2】:

    一切精彩都很简单

    if int(1700 / 1000) == int(1): 
       lst.append("T")
    

    【讨论】:

      【解决方案3】:

      您可以使用// 运算符(整数除法)或使用math 模块中的floor 函数:

      >>> from math import floor
      >>> floor(1.7/1)
      1
      >>> floor(1.7/1) == int(1)
      True
      >>> 1.7 // 1
      1.0
      >>> 1.7 // 1 == 1
      True
      

      【讨论】:

        【解决方案4】:

        你可以试试

        if int(1700/1000) == 1 # I want this to be True
           lst.append("T")
        

        int(1700/1000) 将通过忽略数字的小数部分将 1.7 转换为 1

        【讨论】:

          【解决方案5】:

          你应该看看 floor 和 ceil 函数。 floor 函数舍入到最后一个数字,而 ceil 舍入到下一个数字。在您的情况下,您需要这样做:

          import math
          
          if math.floor(1700 / 1000) == int(1):
             print("TRUE")
          else:
              print("FALSE")
          

          【讨论】:

            【解决方案6】:

            您可以在 Python 中通过 'math' 库中的 'floor' 和 'ceil' 方法向上或向下舍入。

            from math import floor, ceil
            print (floor(1.7), ' , ', ceil(1.7))
            

            结果是

            1 , 2
            

            这适用于 Python 2.x 或 Python 3.x

            【讨论】:

              【解决方案7】:

              // 始终提供 int 值。如果您想始终获得int,请使用它,否则请关注int(a/b)

              if 1700 // 1000 == int(1):  # I want this to be True
                  lst.append("T")
              

              【讨论】:

              • 这是因为 / 进行浮点除法和 // 进行整数除法。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2014-08-20
              • 2022-01-23
              • 1970-01-01
              • 2016-07-22
              • 2020-10-22
              • 1970-01-01
              • 2013-01-05
              相关资源
              最近更新 更多