2016-09-17 91 views
0

我一直在研究对分数猜测游戏,我想让它自动工作,但代码似乎陷入了循环。为什么循环永远不会退出?

有什么建议吗?

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

你应该通过你的算法“手工”,看看它是什么。正如Kalpesh所说,你已经将“elif ... else”逻辑逆转了。 –

+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逻辑..

希望这会帮助你。

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))