我编写了一些代码来确定 0 到 100 之间的秘密数字。用户告诉机器猜测的数字(范围的一半)要么太高,要么太低,或者恰到好处。根据输入,机器使用二分搜索来调整猜测。当猜测正确时,用户按 c 键,游戏结束。问题是,尽管在“我不理解输入”分支中放置了条件,但当用户按下 c (有效条目)时会触发此分支,这不是第一次猜测。
例如,这是输出-
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 75?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Sorry, I did not understand your input.
Game over. Your secret number was:75
>>>
这是代码-
High=100
Low=0
Guess=50
user_input=0
print('Please think of a number between 0 and 100!')
while user_input != 'c':
print("Is your secret number"+" "+str(Guess)+"?")
userinput = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if user_input == 'h':
High=Guess
Guess= ((High+Low)/2)
if user_input == 'l':
Low=Guess
Guess= ((High+Low)/2)
if user_input != 'h' or 'l' or 'c':
print('Sorry, I did not understand your input.')
print ('Game over. Your secret number was:'''+ str(Guess))
提前致谢。我已经为此绞尽脑汁好几个小时了......