gpt4 book ai didi

Python 双 while 循环不起作用,不知道为什么

转载 作者:太空宇宙 更新时间:2023-11-04 10:55:29 25 4
gpt4 key购买 nike

我知道使用“for”可能会使代码更清晰,但我想了解为什么这段代码不起作用。此外,该代码是对 2008 年 MIT OCW 类练习的改编,其中唯一允许使用的函数是算术函数,if、elif、else、print 和 while。需要指出的是,该代码应该打印出前 1000 个素数。

print '2, '      #Print the prime 2 to set only odd primes.
primesofar=3 #Set 3 as the first prime
primecounter=1 #Mark 3 as the first prime to test until 1000, otherwise the while below should test to 1001
primesupport=1 #Create primesupport with a integer value
while primecounter<1000:
primesupport=primesofar/2 #Create a support counter for test the prime. This counter only had to have the half value of the supposed prime, because we only need to try to divide by the primes that are lower than the half of the suppposed prime. In fact it would be better to test for values that are lower than the square root of the supposed prime, but we can't use square root operation yet.
while primesupport>0:
if primesofar%primesupport == 0:
primesupport=-1 #If the remainer of the division is 0, the number isn't prime because it will have more than two divisors so we set primesupport as -1 to exit the while and increase the current primesofar to the next odd number.
primesofar=primesofar+2
elif primesupport==1: #If primesupport is 1, we tested all the numbers below the half of the supposed prime which means the number is prime. So we print it, set the while exit and increase the number of primes counted and go to the next odd number.
print primesofar+', '
primesofar=primesofar+2
primesupport=-1
primecounter=primecounter+1
else:
primesupport=primesupport-1

感谢您的快速响应,现在我想可能是代码中出现了我看不到的中断。因此,我将尝试写下我认为代码应该做的事情,以便您更容易指出我在哪里犯了错误。开始吧:primesofar 收到 3; primecounter 收到 1,primesupport 收到 1。第一个 while 测试 primecounter 并且由于 primesupport 小于 1000,它进入循环。然后,primesupport 值更改为 1,因为 3/2=1由于 primesupport 大于 0,它进入第二个 while 循环。if 条件为真 (3%1=0) 因此代码进入 if,将 primesupport 更改为 -1 并将 primesofar 增加 2。(现在 primesupport=-1 和 primesofar=5)这里有一个问题,因为它没有打印 3 就离开了,但让我们继续。当它回到第二个时,它会收到一个 False,因为 -1 不大于 0。这将使代码测试第一个 while 并且由于 primecounter 未更改,它将再次进入循环。Primesupport 现在将收到 2(因为 5/2=2)它将进入第二个循环并通过所有循环直到 else 条件。primesupport 将减少一个(primesupport now =1),while 循环将继续进入 elif now。那将打印 5将 primesofar 增加到 7减少 primesupport 以离开 while 循环并增加 primecounter,回到第一个循环并重新开始。我承认除了 3 没有按预期打印外,我看不出我在哪里犯了错误。希望您能指点我。

感谢大家的帮助,尤其是 FallenAngel、John Machin、DiamRem 和 Karl Knechtel 指出了错误并展示了调试方法。

最佳答案

我认为这是问题所在:

你被卡住了,因为 primesofar=3 并且在 python 中 3/2 = 1,所以在 if primesofar%primesupport == 0 中:这是真的,因为 1%1 = 0 在 python 中,在 primesofar 的代码中如果 primesofar 是 1 +2,然后 primesofar 又是 3,你从一个时间跳到另一个时间。

关于Python 双 while 循环不起作用,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com