经管之家首页 答疑首页 Python 【新手】请教有关“找零钱”的习题。
  • 统计与数据分析
  • 经济学
  • 管理学
  • 金融学
  • 财会类
  • 国际贸易类
  • 考研考博与考证
  • 找数据和资料
  • 求职与职场
  • 学术与投稿类
  • 社会生活
  • 其它
几天前,开始学习Python,有一道习题,我编写程序后总是得不到结果。(习题在3楼贴上了)
其他的都对,最后一美分的数量总是少一个。为什么呢?
我的代码如下:

cost = float(input("How much did the item cost: "))
given = float(input("How much did the person give you: "))
change = given - cost
twenty = change // 20
ten = (change - twenty * 20) // 10
five = (change - twenty * 20 - ten * 10) // 5
one = (change - twenty * 20 - ten * 10 -five * 5) // 1
quarter = (change - twenty * 20 - ten * 10 -five * 5 - one * 1) // 0.25
dime = (change - twenty * 20 - ten * 10 -five * 5 - one * 1 - quarter * 0.25) // 0.10
nickel = (change - twenty * 20 - ten * 10 -five * 5 - one * 1 - quarter * 0.25 - dime * 0.10) // 0.05
penny = (change - twenty * 20 - ten * 10 -five * 5 - one * 1 - quarter * 0.25 - dime * 0.10 - nickel * 0.05) / 0.01
print("The person's change is %1.2f"%(change))
print("The bills or the change should be:")
print(int(twenty), "twenties")
print(int(ten), "tens")
print(int(five), "fives")
print(int(one), "ones")
print(int(quarter), "quarters")
print(int(dime), "dimes")
print(int(nickel), "nickels")
print(int(penny), "pennies")


当然,中间定义各面值纸币、硬币的公式可以用别的,这是我几经修改尝试后的最后版本。结果都一样,就是一美分的少一个。好郁闷啊!

另外,请回答的朋友们,别用条件等高级代码。
就用最最基本的加减乘除等运算符号。
我用的版本是Python 3.4
zrz_108
回答于 2014/11/24 08:53
Write a program that computes the minimum number of bills and coins needed to make change for a person. For instance, if you need to give $34.36 in change you would need one twenty, one ten, four ones, a quarter, a dime, and a penny. You don’t have to
compute change for bills greater than $20 dollar bills or for fifty cent pieces. You can solve this problem by doing division, multiplication, subtraction, and converting floats to ints when appropriate. So, when you run the program it should look exactly like this:
How much did the item cost: 65.64
How much did the person give you: 100.00
The person's change is $34.36
The bills or the change should be:
1 twenties
1 tens
0 fives
4 ones
1 quarters
1 dimes
0 nickels
1 pennies
 加载中...