使用while循环计算乘积?
我现在有点搞不清楚状况。我需要写一个循环,来打印出1到50之间所有数字的乘积(也就是把这些数字相乘)。这是我的代码:
def main():
x = 1
total = 0
while x <= 50:
total = total * x
x*=1
print(total)
main ()
可是,Python没有打印出任何东西。有人能告诉我我哪里出错了吗?
3 个回答
0
你的问题是你有一个 while
循环,它永远不会结束:
>>> import time
>>> x = 5
>>> while x < 10:
... x*=1
... print x
... time.sleep(1)
...
5
5
5
5
5
5
...
你这里的 x*=1
是把 x
的值乘以 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()
0
x*=1 结果会导致无限循环
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
加一,而不是乘以。