gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:03:03 25 4
gpt4 key购买 nike

在 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

关于Python3 分区 : return int when there's no remainder and a float when there is a remainder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36637207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com