我知道一分钱的价值是.01,但是python将其读作.100000000001我认为是问题所在.
任何帮助表示赞赏,这里是我需要舍入的部分:
# get the amount to change from the userchange = input("Please enter the amount to change: $")print "To make change for $",change,"give the customer back:"# calculate number of twentIEstwentIEs = int(change/ 20)print twentIEs,"twentIEs"change = change - twentIEs *20# calculate tenstens = int(change / 10)print tens,"tens"change = change - tens *10#calculate fivesfives = int(change / 5)print fives,"fives"change = change - fives *5#calculate onesones = int(change / 1)print ones,"ones"change = change - ones * 1#calculate quartersquarters = int(change / .25)print quarters,"quarters"change = change - quarters * .25#calculate dimesdimes = int(change / .10)print dimes,"dimes"change = change - dimes * .10#calculate nickelsnickels = int(change / .05)print nickels,"nickels"change = change - nickels * .05#calculate pennIEspennIEs = int(change / .01)print pennIEs,"pennIEs"解决方法 您遇到的问题是浮点运算不精确的结果.在IEEE浮点中无法精确表示0.01.这是使用货币时不使用浮动的一个原因.
您应该使用小数甚至整数,因为您知道小数点后最多有2位数.在这种情况下,只需要用便士的数量.
关于问题本身,我认为最简单的方法是将美元金额转换为便士金额,然后迭代预定义的值列表,其中包含每种面额的等量硬币(按降序排列):
def change(amount): # this can be removed if you pass the amount in pennIEs # rather than dollars amount = int(round(amount*100)) values = [2000,1000,500,100,25,10,5,1] denom = ['twentIEs','tens','fives','ones','quarters','dimes','nickels','pennIEs'] for i in range(len(values)): num = amount / values[i] amount -= num * values[i] print str(num) + " " + denom[i]
现在调用更改(58.79)将打印
2 twentIEs1 tens1 fives3 ones3 quarters0 dimes0 nickels4 pennIEs
正如codepad.org所见
总结以上是内存溢出为你收集整理的在Python中用便士计算?全部内容,希望文章能够帮你解决在Python中用便士计算?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)