![](/img/trans.png)
[英]For some reason my python code is skipping a certain part of code (pygame)
[英]It seems my code skips a part for no clear reason
我編寫了下面的代碼以在 1 到 100 的數字范圍內打印出 3 和 5 的倍數,但似乎我只繼續獲得 3 的倍數。
counter = 1
for i in range(1, 101):
if 3 * counter == i:
print(i)
counter += 1
elif 5 * counter == i:
print(i)
counter += 1
有人可以幫我解決這個問題。
讓我們看看執行時會發生什么。
counter = 1
i = 1
3 * counter = 3
5 * counter = 5
counter = 1
i = 2
3 * counter = 3
5 * counter = 5
counter = 1
i = 3
3 * counter = 3
printed: 3
counter += 1
counter = 2
i = 4
3 * counter = 6
5 * counter = 10
counter = 2
i = 5
3 * counter = 6
5 * counter = 10
counter = 2
i = 6
3 * counter = 6
printed: 6
counter += 1
如果您想要 3 和 5 的所有倍數,則需要使用模運算符 ( %
)。
count = 0
for i in range(1, 101):
if i % 3 == 0 or i % 5 == 0:
print(i)
count += 1
print(f"counted: {count}")
我會嘗試這樣的事情:
for i in range(1, 101):
if (0 in [i%3, i%5]):
print(i)
%
運算符稱為模運算符,它返回給定除法的余數。
>>> 4 % 2
0
>>> 4 % 3
1
>>> 3 % 4
3
在您的情況下,由於您要搜索的數字是 3或5 的倍數,因此您需要此運算符。
您正在解決 Project Euler #1? 由於這是我會提供幫助的第一個問題,但總的來說,發布整個問題會破壞樂趣,如果您被困在需要幫助的特定部分。
您不想測試您的計數器,因為您基本上是在跟蹤應該除以 3(最小值)以獲得該數字。
counter = 1
for i in range(1, 101):
if i % 3 == 0:
print(i)
counter += 1
if i % 5 == 0:
print(i)
counter += 1
print(f"counted: {counter}")
您的程序無法運行。 當 i==3 時,計數器將增加到 2,當 i==6 時,計數器將增加到 3,依此類推。 計數器可能永遠不會低於 i 的三分之一,因此它永遠不會是 i 的五分之一。
所以,如果你想堅持櫃台的想法,你需要兩個櫃台。 一個五分之一,另一個三分之二:
counter3 = 1
counter5 = 1
for i in range(1, 101):
if (3 * counter3) == i:
print(i)
counter3 += 1
if 5 * counter5 == i:
print(i)
counter5 += 1
但是還有更優雅的方法可以找到可被 3 和 5 整除的數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.