如何改进我的部门计划? (易Python)

时间:2013-06-24 16:58:09

标签: python division

我目前正在尝试制作一个分组程序,要求随机分组问题。有两件事阻止我这样做: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

1 个答案:

答案 0 :(得分:3)

如果您要求num2除以num1,则需要在代码中使用num2/num1,而不是num1/num2。这也是您始终获得0num1始终小于num2的原因,因此当使用整数除法时,num1/num2将为0(这是在Python 2.x上划分整数的默认值。

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

num1 = random.randint(1,12)
num2 = random.randint(1,12) * num1