0

我试图找出用户猜数字的平均次数。用户被问到他们想要做多少问题,然后程序会给他们那么多问题。我无法记录他们猜错和猜错以及猜对并找到两者之间的平均值的次数。这是我到目前为止所拥有的

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

谢谢!

4

2 回答 2

1

所以我试图尽可能少地改变,以免束缚你的风格。所以这样想,得到正确答案所需的平均猜测次数就是猜测的总数除以正确猜测的次数。因为您确保用户最终得到正确答案,所以正确猜测的数量就是问题的数量!

因此,每次运行 HOOBLAH() 时,都会返回获得正确答案所需的猜测次数。在 for 循环之外将所有这些加在一起,然后在循环结束时,将猜测的数量除以问题的数量,然后你就得到了答案!另外,我不认为 python 支持'+=',所以你可能需要将 AVGcounter+=1 更改为 AVGcounter = AVGcounter +1,但我完全可能弄错了,我在语言之间切换了一堆!

一个注意事项是我将 numGuesses 转换为浮点数( 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()
于 2013-04-18T05:47:42.597 回答
0

我不完全确定你要做什么,但如果你想给用户 x 个问题,并找到每个问题的平均猜测次数,你会希望你的 HOOBLAH() 函数返回数字每次运行的猜测。您可以在方法调用之外跟踪它并在最后对其进行平均。但是现在,您的程序无法访问 AVGcounter,这似乎是您用来计算猜测次数的变量,在 HOOBLAH() 函数调用之外。

于 2013-04-18T05:40:39.557 回答