簡體   English   中英

While循環求出乘積(乘法)?

[英]While Loops for figuring out product (multiplication)?

我似乎無法弄清楚。 我應該編寫一個while循環,該循環將打印(乘)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乘以1永遠不會改變它。 數學上, x * 1 -> x

此外,如果您嘗試將數字乘以1到50,則不需要這樣做:

total = 0
for some condition:
    total = total * something

因為total永遠保持為零。 數學上, x * 0 -> 0

用於獲取數字1到50的乘積的正確偽代碼(看起來很像 Python)是:

product = 1
for number = 1 through 50 inclusive:
    product = product * number

更改代碼以使其匹配需要兩件事:

  • total應從1開始。
  • 您應該在循環中將 x 1而不是相乘。

x * = 1導致無限循環

您的問題是您有一個while循環永遠不會退出:

>>> import time
>>> x = 5
>>> while x < 10:
...     x*=1
...     print x
...     time.sleep(1)
... 
5
5
5
5
5
5
...

您的x*=1x值乘以1,實際上什么也沒做。 因此,您正在調用while循環,直到x為50,但x永不改變。 相反,您可能想輸入x+=1 ,這會將x 加1

在您的代碼中,您還想更改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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM