我的代碼似乎工作到WHILE循環之前的行。這個想法是讓計算機通過從最低和最高數量的先前猜測中挑選一箇中間數字來猜測玩家1輸入的數字('P1')。我不知道爲什麼它保持循環!Python - 雖然循環不會停止
import random
P1 = raw_input("The number should be between 0 to 100: \n")
P1 = int(P1)
previousguess = []
count2 = 0
for c in range(2):
cg2 = random.randint(0,100)
print "Computer has guessed: %d" %cg2
if P1 != cg2:
previousguess.append(cg2) #adding the guess into "Previous Guess" list
print previousguess
mn = min(previousguess)
mx = max(previousguess)
while True:
if P1 != cg2:
cg2 = (mn+mx)/2 #guess based on middle of highest and lowest
print "Computer has guessed: %d" %cg2
previousguess.append(cg2)
count2+=1
else:
print "The Computer has guessed it in %d times" %count2
你永遠不會終止循環。當計算機獲得正確的猜測時,if條件失敗,程序永遠不會做任何事情。 – Prune
嗨..感謝您的意見..我已經嘗試過給出的每個建議,但我仍然無法停止while循環..它只計算中間一次,並繼續循環無限的結果。 – chwps
正如我在我的回答中所說的,您必須正確更新mn&mx。您的原始代碼根本不會更新它們,並且它使用的更新對二進制搜索算法無效。如果你需要更多的幫助,你必須遵循指導方針 - 最值得注意的是,發佈你的新代碼。 – Prune