我似乎無法弄清楚這一點。我應該寫了一個循環,將打印1和50.這是我的代碼之間的數的乘積(乘):循環用於計算乘積(乘法)?
def main():
x = 1
total = 0
while x <= 50:
total = total * x
x*=1
print(total)
main()
然而,Python是不打印任何東西。誰能告訴我我做錯了什麼?
我似乎無法弄清楚這一點。我應該寫了一個循環,將打印1和50.這是我的代碼之間的數的乘積(乘):循環用於計算乘積(乘法)?
def main():
x = 1
total = 0
while x <= 50:
total = total * x
x*=1
print(total)
main()
然而,Python是不打印任何東西。誰能告訴我我做錯了什麼?
x = 1
while x <= 50:
x*=1
這些聲明從而導致無限循環,因爲通過一個乘以x
永遠不會改變它。在數學上,x * 1 -> x
。
另外,如果你想通過一個五十至倍增的數字,你不希望這樣的:
total = 0
for some condition:
total = total * something
因爲total
將永遠保持爲零。在數學上,x * 0 -> 0
。
正確的僞代碼(這看起來非常像的Python)用於獲取數字一至第五是產品:
product = 1
for number = 1 through 50 inclusive:
product = product * number
改變你的代碼相匹配,需要兩兩件事:
total
應該從一開始。x
在循環而不是相乘。謝謝!似乎很明顯,現在! – Kjc21793
你的問題是,你有一個while
循環,永遠不會退出:
>>> import time
>>> x = 5
>>> while x < 10:
... x*=1
... print x
... time.sleep(1)
...
5
5
5
5
5
5
...
你x*=1
由1乘以x
值,有效地無所事事。因此,您正在呼叫您的while
循環,直到x
爲50,但x
永不改變。相反,你可能想把x+=1
,這將加1到x
。
在您的代碼中,您還需要更改total = 0
,因爲我們沒有添加,所以我們正在相乘。如果total
爲0,我們實際上正在調用0*1*2*3*4...
,並且由於任何時間0都是0,所以這是無用的。因此,我們設置total
到1
:
def main():
x = 1
total = 1 #Start off at 1 so that we don't do 0*1*2*3*4...
while x <= 50:
total = total * x
x+=1
print(total)
main()
這種形式運行:
>>> def main():
... x = 1
... total = 1 #Start off at 1 so that we don't do 0*1*2*3*4...
... while x <= 50:
... total = total * x
... x+=1
... print(total)
...
>>> main()
'X * = 1'什麼也不做(x次1等於x!),你的意思是'X + = 1'。 – Blorgbeard
當然!現在看起來很明顯!謝謝!!! – Kjc21793