Skip to main content
 首页 » 编程设计

Python- 卡在猜谜游戏的程序上

2025年05月04日9softidea

所以,我已经研究这个猜谜游戏问题一段时间了,在过去的 2 个小时里,我一直在绞尽脑汁,试图找出问题所在,但我做不到。我也尝试搜索解决方案,但我不想复制和粘贴,我实际上想自己解决我的代码。

这是我到目前为止能够得到的:

start = 0 
end = 100 
print 'Please think of a number between 0 and 100!' 
user = '' 
ans = (start + end) / 2 
 
while user != 'c': 
    print ('Is your secret number ' +  str((start + end) / 2) + '?') 
    user = 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 == 'l': 
        start = ans 
    elif user == 'h': 
        end = end - ans 
    ans = start 
print 'Game over. Your secret number was: ' + str((start + end) / 2) 

我做错了什么? 编辑:游戏应该像这样运行:

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. l 
Is your secret number 87? 
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. h 
Is your secret number 81? 
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 84? 
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. h 
Is your secret number 82? 
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 83? 
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 
Game over. Your secret number was: 83 

请您参考如下方法:

你正在设置 ans = start,那是错误的。既然你想自己解决这个问题,我就不多说了。这就是导致您的程序永远不会低于 25 的原因:

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. h 
Is your secret number 25? 
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. h 
Is your secret number 25? 
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. h 
Is your secret number 25? 
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. h 
Is your secret number 25?