[英]ZeroDivisionError: integer division or modulo by zero
我正在構建一個簡單的算法來查找兩個給定數字之間的公約數:
i = int(input("digite o 1o inteiro positivo: "))
j = int(input("digite o 2o inteiro positivo: "))
#i,j = 9,6
aux, cont = 1, 0
if i > j: # 9 < 6
for n in range (i+1): # n = (1,2,3,4,5,6,7,8,9)
while n <= i: # (1,2,3,4,5,6,7,8,9)
if i % n == 0 and j % n == 0: # 9 % (1,3,9) e 6 % (1,3,6)
print(n) # print(1,3)
為什么我的程序有這個ZeroDivisionError
?
從1開始你的range()
,而不是0:
for n in range(1, i + 1): # n = (1,2,3,4,5,6,7,8,9)
i, j = 9, 6
if i > j: # 9 < 6
for n in range(1, i + 1): # n = (1,2,3,4,5,6,7,8,9)
if i % n == 0 and j % n == 0: # 9 % (1,3,9) e 6 % (1,3,6)
print(n) # print(1,3)
1
3
我實際上只是想在你的問題中縮進代碼,但我最終意外地修復了它。 所以,這是一個有效的解決方案:
i = int(input("Give the first positive integer: "))
j = int(input("Give the second positive integer: "))
r = j
if i < j:
r = i
for n in range (2, r + 1):
if i % n == 0 and j % n == 0:
print(n)
輸出:
Give the first positive integer: 27
Give the second positive integer: 18
3
9
范圍從2
開始,因為1
是一個單位,因此作為除數沒有意義(它無論如何都會划分所有內容)。 不應該檢查0
,因為它不會划分任何東西,因為它會導致Div-by-zero錯誤。
無論如何......刷新一些蟒蛇......
你的循環從0
開始,所以出現ZeroDivisionError
。
exception ZeroDivisionError當除法或模運算的第二個參數為零時引發。 關聯值是一個字符串,表示操作數的類型和操作。 [資源]
你必須從1
開始你的for循環
像這樣: for n in range(1,i+1):
而且你不必做while loop
這將是無限的。
你的代碼將是:
i = int(input("digite o 1o inteiro positivo: "))
j = int(input("digite o 2o inteiro positivo: "))
# i,j = 9,6
aux, cont = 1, 0
if i > j: # 9 < 6
for n in range (1,i+1): # n = (1,2,3,4,5,6,7,8,9)
#while n <= i: # (1,2,3,4,5,6,7,8,9)
if i % n == 0 and j % n == 0: # 9 % (1,3,9) e 6 % (1,3,6)
print(n) # print(1,3)
或者您也可以在try-except
塊中編寫代碼,這樣會產生相同的輸出:
i = int(input("digite o 1o inteiro positivo: "))
j = int(input("digite o 2o inteiro positivo: "))
# i,j = 9,6
aux, cont = 1, 0
if i > j: # 9 < 6
for n in range (i+1): # n = (1,2,3,4,5,6,7,8,9)
try:
if i % n == 0 and j % n == 0: # 9 % (1,3,9) e 6 % (1,3,6)
print(n) # print(1,3)
except ZeroDivisionError:
n+= 1
digite o 1o inteiro positivo: 9
digite o 2o inteiro positivo: 6
1
3
函數range()最多可以包含3個參數:
范圍(包括初始限制,不包括最終限制,步驟)
如果僅使用一個參數用於范圍(y)中的x,並且此類情況等於:對於范圍(0,x,1)中的y,包括:[0,1,...,x - 1]
如果你需要用1開始你的范圍,你需要定義它:y在范圍內(1,y)
如果需要更改范圍步長,還需要定義它:對於范圍內的y(0,-50,-1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.