0

我目前正在尝试制作一个询问随机除法问题的除法程序。有两件事阻止我这样做:1)我的程序认为所有东西除以某物总是0。例如8除以2 = 0。2)我需要在没有浮点的情况下进行除法,比如144/5。所以这里是:

import sys 
import random

guessRight=0
guessWrong=0

while True: 
    num1 = random.randint(0,12)    #probably messed up here
    num2 = random.randint(12,144)  #and here  
    print "To exit this game type 'exit'" 
    theyputinstuffhere = raw_input("What is " + str(num2) + " divided by " + str(num1) + "? ") #maybe messed up here


    if theyputinstuffhere == "exit":
        print "Now exiting game!"
        sys.exit()

    elif int(theyputinstuffhere) == num1/num2: #maybe messed this whole elif too
        print num1/num2
        print "Correct!"
        guessRight=guessRight+1
        print "You have gotten " + str(guessRight) + " answer(s) right and you got " + str(guessWrong) + " wrong"
    else:
        print "Wrong! The correct answer is: " + str(num1/num2)
        guessWrong=guessWrong+1
        print "You have gotten " + str(guessRight) + " answer(s) right and you got " + str(guessWrong) + " wrong"

这是它当前打印的内容:

To exit this game type 'exit'
What is 34 divided by 11? #I type any number (e.g. 3)
Wrong! The correct answer is: 0
You have gotten 0 answer(s) right and you got 1 wrong
4

1 回答 1

3

如果您要求 num2 除以 num1,那么您需要num2/num1在代码中使用,而不是num1/num2. 这也是为什么你总是得到,0总是num1小于使用整数除法时(这是 Python 2.x 上除法的默认值)。num2num1/num20

为了避免像 144/5 这样的问题并消除除以零的问题,您可以使用以下方法:

num1 = random.randint(1,12)
num2 = random.randint(1,12) * num1
于 2013-06-24T17:03:35.963 回答