检查数字是否可以在python中被另一个整数整除

时间:2019-11-18 11:10:52

标签: python math

我想检查以下内容

此设置有效

number = 100
divisor = 10

这些不是

number = 100
divisor = 0.1

方案1显示正确答案,但是方案2没有。显示正确结果的最佳方法是什么。

def isDivisible(number, divisor):
    return (number % divisor)

number = 100
divisor = 10

print("Scenario 1:")
print("")
print("Number = " + str(number))
print("Divisor = " + str(divisor))
print("")
print("Answer:")
if isDivisible(number, divisor) == 0:
    print("Answer: True")
    print("Value: " + str(isDivisible(number, divisor)))
else:
    print("Answer: False")
    print("Value: " + str(isDivisible(number, divisor)))

print("")
print("##################")
print("")

number = 100
divisor = 0.1

print("Scenario 2:")
print("")
print("Number = " + str(number))
print("Divisor = " + str(divisor))
print("")
print("Answer:")
if isDivisible(number, divisor) == 0:
    print("Answer: True")
    print("Value: " + str(isDivisible(number, divisor)))
else:
    print("Answer: False")
    print("Value: " + str(isDivisible(number, divisor)))

print("")

2 个答案:

答案 0 :(得分:3)

根据示例,您使用的是浮点数。浮点数有很多限制-最重要的是,它们的精度受到限制。坦率地说,即使可行,我也对浮点模量感到惊讶。它可能应该是TypeError

尝试使用Python标准库中的decimal package,看看是否有更多的成功。

答案 1 :(得分:0)

不确定这是否是正确答案,但似乎可以正常工作。我使用数字作为字符串转换为十进制。我尝试仅使用十进制而不转换为字符串,但是在“ number”变量的末尾有很多垃圾,因此无法解决。

from decimal import Decimal # Added this

def isDivisible(number, divisor):
    return (number % divisor)

number = 10
divisor = 0.0001
divisor = Decimal(str(divisor))
number = Decimal(str(number))

print("Number = " + str(number)) # Added this
print("Divisor = " + str(divisor)) # Added this
print("")
if isDivisible(number, divisor) == 0:
    print("Answer: True")
    print("Value: " + str(isDivisible(number, divisor)))
else:
    print("Answer: False")
    print("Value: " + str(isDivisible(number, divisor)))

print("")