繁体   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