如果数字除以完美,则为整数,Python

问题描述 投票:1回答:5

如果两个数字之间出现完美除法,我希望将结果转换为整数,但是如果两个数字之间没有出现完美除法,则不应进行任何更改。例如,6/2给出结果3.0。由于这是完美的除法,因此应将3.0转换为3。另一方面,如果我有14/4给出结果3.5,则应该保持原样,因为没有发生完美除法。

这里是完美除法,我的意思是a除以​​b得到一个整数

python division
5个回答
2
投票
def divide_and_conquer(a, b): return a / b if a % b else int(a/b)

0
投票
# the numbers num = 34 divisor = 17 # do the division modula = num//divisor # modulus quotient = num/divisor # normal division # check if division is perfect if modula == quotient : result = int(quotient) else: result = quotient

0
投票
a = 6 b = 2 if a % b == 0: result = a // b else: result = a / b

也就是说,您也可以简单地运行标准除法,并将结果也转换为整数...

result = a / b
if result % 1 == 0:
  result = int(result)

但是,在这两种情况下,您可能都希望检查编码的更广泛的上下文,因为如果变量有时是一种数据类型,而有时是另一种数据类型,则可能会在线下产生实际问题。 -最好在每种情况下都将值保留为浮点型,直到需要将其变为整数为止。

注意:在两个整数之间使用'//'不能完美地除以仍然会得到一个整数,因为python只会忽略其余部分。 6 // 4 = 1,15 // 2 = 7。    

0
投票
def divide(a, b): return a / b if a % b else a//b divide(2, 5) # 0.4 (float) divide(10, 5) # 2 (int)
© www.soinside.com 2019 - 2024. All rights reserved.