2015-04-12 53 views
-1

我知道我重新發布了一個類似的問題,但我更改了代碼,並且在處理猜測高或低時遇到問題。當我得到輸出後,它會在第三次猜測後退出,並且它會提供比以前更高的數字或更低的數字。我的數字是8,它會猜測12,我說它的高,並給出25作爲下一個猜測。我將如何解決這個問題?我如何計算猜測次數,因爲它不計數?針對comupter的猜測遊戲,修復高低數字

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

回答

0

正在發生的事情是,你的初始高變量被設置爲100。12(使用例),它由2.新的高除以它的猜測之後50。因此,25仍然是一個有效的猜測。你應該做的是爲新的變量重新設置爲其猜測:

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

這將確保在未來的猜測下降比其先前的猜測更低。當它猜測低時,應該對低變量做類似的事情:

​​
+0

謝謝!它糾正了這個問題。我可以爲伯爵做些什麼? – get2thechopper

+0

設置一個計數器。在while循環之前聲明一個int變量,並將其設置爲0.之後,每循環一次,在開始時,通過執行將變量加1(例如,如果變量是i):i + = 1。也有函數返回猜測計數,並且你可以在main()中打印,或者在獲得函數後打印它。 – MLavrentyev

+0

好的,謝謝你的指導,並會做! – get2thechopper