我将以下代码用Python编写为项目。我把计算机科学作为GCSE。我是新手,所以不知道如何修复这个bug。当我输入我的第一个猜测时,例如'5',它会说太高。然后,一旦游戏完成,它会说答案是7.这是一个我一直试图解决但无法完成的错误。这是我使用的代码:
import random
numberofGuesses = 0
print ("I'm thinking of a number between 1 and 10. What is it? You have three guesses.")
while numberofGuesses < 3:
numberofGuesses = numberofGuesses +1
randomNumber = (random.randint(1,10))
userInput = 0
userInput = input ()
userInput = int(userInput)
if randomNumber > userInput:
print("Too Low! Try again")
if randomNumber < userInput:
print("Too High! Try Again")
if numberofGuesses == 3:
print("Sorry! You lose. The correct number was:",randomNumber)
if randomNumber == userInput:
print("Well Done! Your guess was correct!")`
除了我提到的一个bug之外,这段代码完美无缺。
答案 0 :(得分:7)
每次进行猜测时,您都会重新选择一个随机数。相反,我相信您希望程序首先选择一个数字,然后输入您的while循环。
randomNumber = (random.randint(1,10))
while numberofGuesses < 3:
numberofGuesses = numberofGuesses +1
userInput = 0
userInput = input ()
userInput = int(userInput)
if randomNumber > userInput:
print("Too Low! Try again")
if randomNumber < userInput:
print("Too High! Try Again")
答案 1 :(得分:3)
除了在每次迭代中重置随机数之外还有另一个问题:
如果猜测正确,你不会停止循环。你应该在猜测评估之后增加猜测计数器,否则你将无法判断第三次尝试是否有人正确猜测:
import random
numberofGuesses = 0
randomNumber = (random.randint(1,10))
print("I'm thinking of a number between 1 and 10. What is it? You have three guesses.")
while numberofGuesses < 3:
userInput = int(input())
if randomNumber > userInput:
print("Too Low! Try again")
elif randomNumber < userInput:
print("Too High! Try Again")
else: # Correct guess!
break
numberofGuesses = numberofGuesses +1
else: # Executed only if the while loop is not exited via "break"
print("Sorry! You lose. The correct number was:",randomNumber)
if randomNumber == userInput:
print("Well Done! Your guess was correct!")
答案 2 :(得分:1)
您正在将randomNumber设置为每个猜测的新随机数 - 因此,对于第一个答案,它可能是7,然后您进行猜测并将其更改为3.要解决此问题,请移动randomNumber = (random.randint(1,10))
在你的while循环之外 - 做一次,而不是每次猜测一次。干杯,祝你学习愉快!