[英]Find all positive numbers divisible by 10 and less than n
我需要找到所有可被 10 整除且小於 n 的正數,我發現了一個具有相同問題的字符串,但我很難解釋它,因為用戶使用的是 java,因此代碼非常不同且令人困惑。
我試圖通過將我檢查過的代碼拼湊在一起來制作一個代碼,但它只有在它可以被其他數字整除時才有效,如果它是 10,它將以 0 永遠持續下去。
n = int(input("Enter a number: "))
x = 0
while x < n :
r = n % 10
if r % 10 != 0 :
x = x + r
print("positive numbers divisible by 10 ", x)
下面是更簡單的代碼,它有助於獲得可被 10 整除且小於 n 的數字列表:
n = int(input("Enter a number n: "))
divisibleBy10 = []
for i in range(0, n):
if i % 10 == 0:
divisibleBy10.append(i)
print(divisibleBy10)
你可以這樣做:
n = 100
i = 0
while i<n:
if i%10==0:
print(i)
i+=1
下面的這段代碼試圖減少循環次數。 如果“x”非常大,則有助於優化解決方案。 這個想法是不要對從 1 到 n-1 的每個數字進行可分性檢查。 在這里,我們使用可被 10 整除的最小正數是 10。下一個感興趣的數是 10 + 10 = 20,因此跳過數字 11 到 19。這有助於提高性能。
x = input('Enter any number ')
y = 10
while y < x:
print(y)
y = y + 10
您還可以嘗試以下操作:
# grab the user's input
n = int(input('please enter a number: '))
# set x to 0, so the while loop can stop when 'n' is greater than '0'
x = 0
while n > x:
if n % 10 == 0:
print('{} is divisible by 10.'.format(n))
n -= 1
所以基本上循環以用戶輸入的值進入,比方說10
。
10
大於0
嗎? 是的(while 循環執行), if
語句使用mod
計算余數。 打印該值是因為 if 語句計算True ,余數等於0。 最后,n減19
大於0
嗎? 是的(while 循環執行), if
語句使用mod
計算余數。 該值未打印,因為 if 語句計算False ,余數不等於零。 最后,n減18
大於0
嗎? 是的(while 循環執行), if
語句使用mod
計算余數。 該值未打印,因為 if 語句計算False ,余數不等於零。 最后,n減1...
依此類推,直到n達到0
,while 循環停止,因為0
不大於0
。
我認為使用內聯 for 循環:
print([i for i in range(10,n,10) if i % 4 == 0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.