2013-06-24 18 views
0

我目前正在嘗試做一個分區程序,詢問隨機分區的問題。有兩件事情阻止我這樣做:1)我的程序認爲,按某事劃分的所有東西總是爲0。 8除以2 = 0. 2)我需要劃分沒有浮點數,比如144/5。所以在這裏,它是:如何改進我的分區程序? (Easy Python)

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 
+2

'num1'總是比'num2'小。你可能混淆了這些值。 – Matthias

+0

請注意,提示符(「num2除以num1」)和檢查(num1/num2)不是說同樣的事情。 –

+0

@Matthias查看輸入行,似乎正是這種情況。在該行中,它打印'/'。 – JAB

回答

3

如果你所要求的NUM2 NUM1通過分成,那麼你需要在你的代碼,而不是num1/num2使用num2/num1。這也是爲什麼你總是得到0,num1將總是小於num2所以num1/num20當使用整數除法(這是在Python 2.x除以整數的默認值)。

要避免的問題,如五分之一百四十四和零問題消滅分裂,你可以使用以下命令:

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

FJ我看到了我的錯誤,但是當我回答它時,只要它詢問我144/0就說:Traceback(最近一次調用最後一個): 文件「./division.py」,第19行,在 elif int(theyputinstuffhere)== num2/num1: ZeroDivisionError:整數除或零除 – user2468523

+0

此外,它會詢問奇怪的問題,如144/5,這是...不是我想要的,我想要的是144/12或24/6或類似的東西... – user2468523

+0

我看到'ZeroDivisionError'可以通過在第八行代碼中將0更改爲1來解決。 – user2468523

相關問題