说明是
创建一个程序,允许他输入一定量的更改,然后打印需要多少季度,硬币,镍币和便士来弥补所需的金额。例如,如果他输入1.47,该程序将告诉他需要5个季度,2个角钱,0个镍币和2个便士。
我真的不知道该怎么做但是我试了一下。我真的不确定该怎么做。
print "Change Calclator"
quarter = .25
dime = .10
nickel = .5
penny = .1
moneygiven = raw_input("Enter how much money given: ")
citem = raw_input("How much did the item cost?: ")
moneygiven = float(moneygiven)
citem = float(citem)
moneyback = moneygiven - citem
qmb = moneyback % quarter
partialtotal = moneyback - qmb * quarter
dmb = partialtotal / dime
dpartialtotal = partialtotal - dmb * dime
nmb = dpartialtotal / nickel
npartialtotal = dpartialtotal - nmb * nickel
pmb = npartialtotal / penny
ppartialtotal = npartialtotal - pmb * penny
print "You need %s quarters, %s dimes, %s nickels, %s pennies." % (qmb, dmb, nmb, pmb)
如果以20美元的金钱和19.45的citem运行它就会给出这一点
Change Calclator
Enter how much money given: 20
How much did the item cost?: 19.45
You need 2.2 quarters, 0.0 dimes, 0.0 nickels, 0.0 pennies.
开发@ jonrsharpe的评论,你应该使用持有便士的int
变量。这里的要点是你有一个具有浮点值的整数金币,你在分割时混合它们,从而得到奇怪的值。还要考虑到您应该使用正确的除法运算符。
这是一个工作版本:
print "Change Calclator"
quarter = 25
dime = 10
nickel = 5
penny = 1
moneygiven = raw_input("Enter how much money given: ")
citem = raw_input("How much did the item cost?: ")
moneygiven = int(float(moneygiven) * 100)
citem = int(float(citem) * 100)
moneyback = moneygiven - citem
qmb = moneyback / quarter
partialtotal = moneyback - qmb * quarter
dmb = partialtotal // dime
dpartialtotal = partialtotal - dmb * dime
nmb = dpartialtotal // nickel
npartialtotal = dpartialtotal - nmb * nickel
pmb = npartialtotal // penny
ppartialtotal = npartialtotal - pmb * penny
print "You need %s quarters, %s dimes, %s nickels, %s pennies." % (qmb, dmb, nmb, pmb)
您应该使用//运算符代替/运算符。另外一件事你把penny = .1和penny = 0.10相同。你应该使用0.01
// Floor Division - 操作数的除法,其结果是删除小数点后的数字的商。
例:
a=.25
.55//a = 2.0
代码工作
print "Change Calclator"
quarter = .25
dime = .10
nickel = .05
penny = .01
moneygiven = raw_input("Enter how much money given: ")
citem = raw_input("How much did the item cost?: ")
moneygiven = float(moneygiven)
citem = float(citem)
moneyback = moneygiven - citem
qmb = moneyback // quarter
partialtotal = moneyback - qmb * quarter
dmb = partialtotal // dime
dpartialtotal = partialtotal - dmb * dime
nmb = dpartialtotal // nickel
npartialtotal = dpartialtotal - nmb * nickel
pmb = npartialtotal // penny
ppartialtotal = npartialtotal - pmb * penny
print "You need %s quarters, %s dimes, %s nickels, %s pennies." % (qmb, dmb, nmb, pmb)