在 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
我是一名优秀的程序员,十分优秀!