📜  “在 python 中除法时如何获取数字的余数” - Python (1)

📅  最后修改于: 2023-12-03 15:06:09.329000             🧑  作者: Mango

在 Python 中除法时如何获取数字的余数

在 Python 中,我们可以使用取模运算符 % 来获得两个数字相除的余数。以下是一些示例:

示例代码
# 获取两个数字相除的余数
x = 10
y = 3
result = x % y
print("The remainder of", x, "divided by", y, "is", result)

# 从用户输入中获取数字并计算余数
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
remainder = numerator % denominator
print("The remainder of", numerator, "divided by", denominator, "is", remainder)
结果
The remainder of 10 divided by 3 is 1
Enter the numerator: 25
Enter the denominator: 4
The remainder of 25 divided by 4 is 1

注意:在使用取模运算符时,如果第二个数字为零,Python 会引发 ZeroDivisionError 异常。

参考资料