猜测计算机的游戏,修复高或低的数字

时间:2015-04-12 19:43:07

标签: python python-3.x

我知道我重新发布了一个类似的问题,但是我更改了代码,并且我在处理猜测高或低时遇到了问题。当我得到输出时,它在第三次猜测后退出,它给出的数字比以前更高,甚至更低。我的数字是8,它将猜测12,我说它的高,并给出25作为下一个猜测。我该如何解决这个问题?我如何计算猜测次数,因为它不算数?

from random import randint

def computer_guess(num):

    low = 1
    high = 100
    newGuess = 0
    guess = randint(1,100)
    while guess != num:
        newGuess = randint(low,high)
        print("The computer takes a guess...", newGuess)
        ans = input("Is the number L for low, H for High, or C for correct? ")
        if (ans == "H" or ans == "h"):
            if(high/2 > num):
                high = high/2
            else:
                high = high-1            


        elif (ans == "L" or ans == "l"):
            if(low*2 < num):
                low = low*2
            else:
                 low = low +1
        elif (ans == "C" or ans == "c"):
            ans = "Correct"
            guess = num;
            print(str(high) + "|" + str(low) + "|" + str(newGuess))


    print("The computer guessed", guess, "and it was correct!")
    print(" I computron won the battle")


def main():

    num = 0
    print("I am computron, I accept your guessing game!")
    num = int(input("\n\nChoose a number for the computer to guess: "))
    if num < 1 or num > 100:
        print("Must be in range [1, 100]")
    else:
        computer_guess(num)

    print("guesses count: " + str(num))


    play_again = input("would you like to play again(yes or no)? ")
    if play_again == "yes" or play_again == "y" or play_again == "Y":
        main()
    if play_again == "no" or play_again == "n" or play_again == "N":
        exit()



if __name__ == '__main__':
main()

1 个答案:

答案 0 :(得分:0)

发生的事情是您的初始高变量设置为100.在猜测12(使用您的示例)后,它将其除以2.新的高值为50.因此,25仍然是有效的猜测。你应该做的是将新的高变量重置为它的猜测:

if(ans == "H" or ans == "h"):
    high = newGuess

这将确保下一次猜测低于之前的猜测。当猜测低变量时,应该对低变量做类似的事情:

elif(ans == "L" or ans == "l"):
    low = newGuess