为什么循环永远不会退出?

时间:2016-09-17 16:57:25

标签: python python-3.x

我一直在研究Bisectional Number猜测游戏,我想让它自动运行,但代码似乎陷入了循环。

有什么建议吗?

x = 75

low = 0
high = 100

guessing = True

while guessing:

    guess = int((high + low) // 2)

    if guess == x:
        guessing = False
    elif guess < x:
        high = guess
    else:
        low = guess

print("Your number is ", str(guess))   

2 个答案:

答案 0 :(得分:0)

我认为它会起作用:

x = 75
low = 0
high = 100
guessing = True
while guessing:
    guess = (high + low) // 2
    print("guess:",guess)
    if guess == x:
        guessing = False
    elif guess < x:
        low = guess
    else:
        high = guess
print("Your number is ", guess) 

输出:

guess: 50
guess: 75
Your number is  75

您不需要显式将其转换为int,因为您在此使用整数除法guess = int((high + low) // 2)并反转elif ..else逻辑..

希望这会对你有所帮助。

答案 1 :(得分:0)

对于这样的事情,最好限制可能的迭代次数。

max_iter = 25
x = 42
low , high = 0 , 100

for _ in range(max_iter):
    guess = (high + low) // 2
    if guess == x:
        break
    low , high = (guess , high) if x > guess else (low , guess)

print("Your number is {}".format(guess))   
相关问题