如何使用模数来查找 python 中的一个数是否可​​以被第二个数整除?

How to use modulo to find if one number is divisible by the second in python?

我是 python 的新手,一直在尝试解决我在网上找到的问题,但我被困在一个问题上:

"Write a program which takes two integers as input. If the first is exactly divisible by the second (such as 10 and 5 or 24 and 8, but not 10 and 3 or 24 and 7) it outputs “Yes”, otherwise “No”, except when the second is zero, in which case it outputs “Cannot divide by zero”. Remember you can use the modulo operator (“%”) to find out whether one number is divisible by another."

以下代码可能对您有所帮助:

first_number = int(input())
second_number = int(input())
if first_number % second_number == 0:
     print('Yes')
else:
     print('No')

通过取模,您可以求出两个数相除的余数,如果余数为零,则可以得出它们可整除的结论。 要处理 zero 情况,您可以使用以下代码:

first_number = int(input())
second_number = int(input())
if second_number == 0:
     print('Cannot divide by zero')
elif first_number % second_number == 0:
     print('Yes')
else:
     print('No')

使用%检查两个数的余数。它会判断值分子是否被分母整除(当 a%b ==0 时)或不整除(当 a%b 不为 0 时)。以另一种方式,您可以使用 /// 运算符,例如 a/b 这将给出 float 类型的整数(商)和 iinteger 类型,例如 4/3 = 1.333 and 4//3=1 然后你可以打印 print(a/b==a//b),在此之前你需要检查分母是否为 0,如果是 0 则抛出错误。 以下是如何检查数字是否可整除的示例

a = int(input())
b = int(input())

if b==0:
    print('Cannot divide by zero')
else:
    val = 'Yes' if a%b==0 else 'No'
    print(val)

或使用:

first_number = int(input())
second_number = int(input())
print(not (first_number % second_number))

首先你需要检查第二个数字是否为零,如果不是则检查模数 见以下代码:

first_number = int(input())
second_number = int(input())
if second_number == 0:
    print("Cannot divide by zero\n")
else:
    if first_number % second_number == 0:
        print('Yes\n')
    else:
        print('No\n')

模运算符的工作原理是将第一个数字除以第二个数字,因此在尝试时得到除零异常是有道理的。

您可以先进行测试以查看是否会导致错误,或者您可以假设用户不会导致错误并在他们发生错误时进行处理。 "Ask forgiveness not permission"俗话说

>>> a = 5
>>> b = 2
>>> a % b
1
>>> a % b == 0
False
>>> c = 8
>>> c % b == 0
True
>>> d = 0
>>> c % d == 0
ZeroDivisionError: ...

>>> try:
...     if int(input("First:")) % int(input("Second:")) == 0:
...         print("yes")
...     else:
...         print("no")
... except ZeroDivisionError:
...         print("Second value was 0")
...
First: 2
Second: 0
Second value was 0