我试图找到用户猜测数字的平均次数。用户被问到他们想要做多少问题然后程序会给他们带来很多问题。我在记录他们猜测和出错的次数时遇到了麻烦,猜测并且正确并找到两者之间的平均值。这就是我到目前为止所拥有的
print("Hello!")
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVGcorrect = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
AVGcorrect+=1
print("Correct!")
AVERAGE+=((AVGcorrect+AVGcounter)/AVGcorrect)
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
numPROBLEMS = input("How many problems would you like to solve? ")
PROBLEMS = int(numPROBLEMS)
if PROBLEMS in range(1,11):
for PROBLEMS in range(PROBLEMS):
HOOBLAH()
else:
print("Average number of tries: {0}".format(HOOBLAH,AVERAGE))
else:
print("Please input a value between 1 through 10!")
main()
谢谢!
答案 0 :(得分:1)
所以我试图尽可能少地改变,以免痉挛你的风格。所以想想这样,获得正确答案所需的平均猜测次数只是猜测的总数除以正确猜测的数量。因为你确保用户最终得到正确答案,正确猜测的数量就是问题的数量!
因此,每次运行HOOBLAH()时,都要返回获取正确答案所需的猜测次数。在for循环之外添加所有这些,然后在循环结束时,将猜测次数除以问题的数量,然后你就得到了答案!另外,我不认为python支持'+ =',所以你可能需要将AVGcounter + = 1更改为AVGcounter = AVGcounter +1,但我完全可能弄错了,我在语言之间切换了一堆!
一个注意事项是我将numGuesses转换为float(float(numGuesses)),这是为了确保int数据类型不会截断你的平均值。例如,你不希望5/2出现2,你希望它是2.5,浮动!
希望这有帮助!
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
print("Correct!")
return AVGcounter
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
problemsString = input("How many problems would you like to solve? ")
numProblems = int(problemsString)
numGuesses = 0
if numProblems in range(1,11):
for problem in range(numProblems):
numGuesses = numGuesses + HOOBLAH()
print("Average number of tries: " + str(float(numGuesses)/numProblems)
else:
print("Please input a value between 1 through 10!")
main()
答案 1 :(得分:0)
我不完全确定你要做什么,但是如果你想给用户x个问题,并找到每个问题的平均猜测次数,你会想要你的HOOBLAH()函数返回每次运行的猜测次数。您可以在方法调用之外跟踪此信息并在结束时对其进行平均。但是现在,你的程序无法访问AVGcounter,它似乎是你用来计算HOOBLAH()函数调用之外的猜测数量的变量。