代码之家  ›  专栏  ›  技术社区  ›  Ray

在Python中使用除法运算符时,如何获取十进制值?

  •  58
  • Ray  · 技术社区  · 16 年前

    >>> 4 / 100
    0
    

    12 回复  |  直到 7 年前
        1
  •  144
  •   Community CDub    8 年前

    有三种选择:

    >>> 4 / float(100)
    0.04
    >>> 4 / 100.0
    0.04
    

    与C、C++、java等行为相同,或者

    >>> from __future__ import division
    >>> 4 / 100
    0.04
    

    您还可以通过传递参数来激活此行为 -Qnew

    $ python -Qnew
    >>> 4 / 100
    0.04
    

    第二个选项是Python 3.0中的默认选项。如果要使用旧的整数除法,必须使用 // 操作人员

    编辑 -Qnew 幸亏 ΤΖΩΤΖΙΟΥ

        2
  •  25
  •   Glyph    16 年前

    其他答案建议如何获取浮点值。虽然这将接近你想要的,但它不会精确:

    >>> 0.4/100.
    0.0040000000000000001
    

    如果你真的想要一个 值,请执行以下操作:

    >>> import decimal
    >>> decimal.Decimal('4') / decimal.Decimal('100')
    Decimal("0.04")
    

    这将给你一个对象,它正确地知道4/100英寸 是“0.04”。浮点数实际上是以2为基数的,即二进制,而不是十进制。

        3
  •  7
  •   Thomas Wouters    16 年前

    将其中一个或两个术语设置为浮点数,如下所示:

    4.0/100.0
    

    from __future__ import division
    
        4
  •  5
  •   S.Lott    16 年前

    您可能想看看Python的 decimal 包,也是。这将提供很好的十进制结果。

    >>> decimal.Decimal('4')/100
    Decimal("0.04")
    
        5
  •  4
  •   moonshadow    16 年前

    您需要告诉Python使用浮点值,而不是整数。您只需在输入中使用小数点即可:

    >>> 4/100.0
    0.040000000000000001
    
        6
  •  1
  •   torial    16 年前

    简单路线4/100.0

    4.0 / 100

        7
  •  1
  •   Jai Narayan    7 年前

    下面我们给出了两种可能的情况

    from __future__ import division
    
    print(4/100)
    print(4//100)
    
        8
  •  0
  •   Martin Cote    16 年前

    试试4.0/100

        9
  •  0
  •   Vasil    16 年前

    用一个整数除以另一个整数不能得到一个十进制值,这样得到的总是一个整数(结果被截断为整数)。您至少需要一个值才能成为十进制数。

        10
  •  0
  •   DaredevilRanon    7 年前

    在代码中添加以下函数及其回调。

    # Starting of the function
    def divide(number_one, number_two, decimal_place = 4):
        quotient = number_one/number_two
        remainder = number_one % number_two
        if remainder != 0:
            quotient_str = str(quotient)
            for loop in range(0, decimal_place):
                if loop == 0:
                    quotient_str += "."
                surplus_quotient = (remainder * 10) / number_two
                quotient_str += str(surplus_quotient)
                remainder = (remainder * 10) % number_two
                if remainder == 0:
                    break
            return float(quotient_str)
        else:
            return quotient
    #Ending of the function
    
    # Calling back the above function
    # Structure : divide(<divident>, <divisor>, <decimal place(optional)>)
    divide(1, 7, 10) # Output : 0.1428571428
    # OR
    divide(1, 7) # Output : 0.1428
    

    Syntex:divide([divident],[divisor],[decimal place(可选))

    divide(1, 7, 10) divide(1, 7)

    如有任何疑问,请在下面发表评论。

        11
  •  0
  •   Appu    6 年前

        12
  •  -1
  •   Marc-André Yelle    5 年前

    它只是删除小数点后的小数部分。

        13
  •  -3
  •   Michail N    7 年前

    从future库导入部门,如下所示:

    from__future__ import division