更改具有确切更改类型的计算器

时间:2014-12-04 14:37:18

标签: python calculator

说明

  

创建一个程序,允许他输入一定数量的更改,   然后打印多少个季度,硬币,镍币和便士   需要弥补所需的金额。例如,如果他输入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.

2 个答案:

答案 0 :(得分:1)

开发@ jonrsharpe的评论,你应该使用持有便士的int变量。这里的要点是你有整数金额的 float 值,并且你在分割时混合它们,从而得到奇怪的值。还要考虑到你应该使用正确的除法运算符。

这是一个工作版本:

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)

答案 1 :(得分:0)

您应该使用//运算符代替/运算符。 另外一件事你把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)