Skip to main content
 首页 » 编程设计

Python3 分区 : return int when there's no remainder and a float when there is a remainder

2025年05月04日15bonelee

在 python3 中,整数除法的工作方式与 python 2.7.3 不同。有没有办法保证除法后没有余数的数返回为int,而除法后有余数的数返回为float?

我希望能够检查:

if (instanceof(x/n, int)): 
    # do something 

在python3中出现如下情况:

>>> 4 / 2 
2.0 
>>> 5 / 2 
2.5 

有没有办法让除法像这样?

>>> 4 / 2 
2 
>>> 5 / 2 
2.5 

请您参考如下方法:

您必须自己实现。显而易见的方法是:

def divspecial(n, d): 
    q, r = divmod(n, d)  # Get quotient and remainder of division (both int) 
    if not r: 
        return q         # If no remainder, return quotient 
    return n / d         # Otherwise, compute float result as accurately as possible 

当然,如果你只是想检查除法是否准确,不要像上面的函数那样使用废话来检查:

if isinstance(divspecial(x, n), int): 

直接测试余数即可:

if x % n == 0:  # If remainder is 0, division was exact