2014-05-02 104 views
0

我似乎無法弄清楚這一點。我應該寫了一個循環,將打印1和50.這是我的代碼之間的數的乘積(乘):循環用於計算乘積(乘法)?

def main(): 
    x = 1 
    total = 0 
    while x <= 50: 
     total = total * x 
     x*=1 
    print(total) 

main() 

然而,Python是不打印任何東西。誰能告訴我我做錯了什麼?

+1

'X * = 1'什麼也不做(x次1等於x!),你的意思是'X + = 1'。 – Blorgbeard

+0

當然!現在看起來很明顯!謝謝!!! – Kjc21793

回答

1
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在循環而不是相乘。
+0

謝謝!似乎很明顯,現在! – Kjc21793

0

X * = 1的結果在一個無限循環

+0

這就是爲什麼。謝謝! – Kjc21793

0

你的問題是,你有一個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,這將加1x

在您的代碼中,您還需要更改total = 0,因爲我們沒有添加,所以我們正在相乘。如果total爲0,我們實際上正在調用0*1*2*3*4...,並且由於任何時間0都是0,所以這是無用的。因此,我們設置total1

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()