2016-11-21 54 views
2

批發禽蛋公司立足於卵的數量它們的價格購買:規劃決策結構

0直到但不包括4打$ 0.50每打4直到但不包括6打$ 0.45每打6直到但不包括11打打擊每打0.40打11打打打0.35打每打額外雞蛋打價格爲每打價格的1/12

創建一個程序,提示用戶雞蛋的數量,然後計算帳單。該應用程序的輸出應該類似於:輸入購買的雞蛋數量:18該法案等於:$ 0.75

這是問題,這裏是我的代碼:

eggs = int(raw_input("Please enter the amount of eggs you have.")) 

if (eggs >=12 and eggs <=47): 
    dozen = int(eggs) // 12 
    dozenprice = float(dozen) * 0.50 
    extra = float(eggs) % 12 
    extraprice = float(extra)*((1/12)*0.50) 
    total = float(dozenprice) + float(extraprice) 
    print "Your total is " + str(total) 

if (eggs >=48 and eggs<=71): 
    dozen = int(eggs) // 12 
    dozenprice = float(dozen) * 0.45 
    extra = float(eggs) % 12 
    extraprice = float(extra)*((1/12)*0.45) 
    total = float(dozenprice) + int(extraprice) 
    print "Your total is " + str(total) 

if (eggs >=72 and eggs <=131): 
    dozen = int(eggs) // 12 
    dozenprice = float(dozen) * 0.40 
    extra = float(eggs) % 12 
    extraprice = float(extra)*((1/12)*0.40) 
    total = float(dozenprice) + int(extraprice) 
    print "Your total is " + str(total) 

if (eggs >=132): 
    dozen = int(eggs) // 12 
    dozenprice = float(dozen) * 0.35 
    extra = float(eggs) % 12 
    extraprice = float(extra)*((1/12)*0.35) 
    total = float(dozenprice) + int(extraprice) 
    print "Your total is " + str(total) 

爲什麼ISN」 t出現額外雞蛋的價格?

+6

Python中的空白問題非常重要,這在語法上不是有效的。 – jonrsharpe

+1

@CliffBurton粘貼的代碼格式不正確。對Python2.7如何解釋'/'正常劃分有一個合​​理的誤解,但從問題不清楚是這個問題。 – TemporalWolf

回答

3

在python2.7 1/120,因爲它們是整數,並使用整數除法你得到0,然後你得到0 * price ...

1/12.會產生0.083,爲12.強制它是一個浮動。 或者,你可以得到Python3行爲like so

from __future__ import division 

不這樣做,在Python2.7,/ & // are equivalent

+2

要添加到此,您可以通過'from __future__ import division'啓動程序來獲得您期望的行爲。 – user3030010

+1

或者將這兩個數字都作爲浮點數來投射。 'float(1)/ float(12)' –

+1

@ user3030010我已經將它添加到描述中。 – TemporalWolf

0

據我瞭解,這是你的Python代碼中的問題。我修改第一部分如下

if (12 <= eggs <= 47): 
    dozen = eggs/ 12 
    dozenprice = dozen * 0.50 
    extra = eggs % 12.0 
    extraprice = extra*((1.0/12.0)*0.50) 
    total = dozenprice + extraprice 
    print "Your total is " + str(total) 

結果是:

Please enter the amount of eggs you have : 18 

Your total is 0.75 

您無需使用extra = float(eggs) % 12,因爲雞蛋值爲整數。將if()變量簡化爲if (12 <= eggs <= 47):