我正在使用Python,我试图将一定数量的以美分为单位的货币转换成25美分、5美分、1美分和1美分的等值货币。在
这是我目前所拥有的,但我发现问题是我不知道如何从硬币中取出剩余的硬币,然后把它分解成一角硬币、五分镍币和一分硬币。我是新手,只是日子不好过。我不是要求别人来解决问题,只要指出我做错了什么(也许我需要做些什么来解决它)。在
# Convert some money to an appropriate collection of cents
penny = 1
nickel = 5
dime = 10
quarter = 25
quarters = 0
dimes = 0
nickels = 0
pennys = 0
cents = int(input("Please enter an amount of money you have in cents: "))
if cents >= 25:
quarters = cents / quarter
cents % quarter
if cents >= 10:
dimes = cents/dime
cents % dime
if cents >= 5:
nickels = cents /nickel
cents % nickel
if cents > 0:
pennys = cents / penny
cents = 0
print ("The coins are: quarters", quarters,\
",dimes", dimes, ",nickels", nickels, ", and pennys.", pennys)
这里需要两个运算:整数除法和模。在
整型除法
A / B
提出了一个简单的问题:B
将干净地放入A
中多少次(而不必将B
拆分成小数部分)?2
适合8
干净4
次。2
也可以干净地放入9
次。在模}。}。在
A % B
提出了相同的问题,但给出了相反的答案:假设A
干净地进入B
若干次,剩下的是什么?2
干净地进入8
次,没有留下任何东西,所以2 % 8
是{2
干净地进入9
次,但1
次,所以2 % 9
是{我再给你举一个例子,让你从这个问题过渡到你的问题。假设给了我一些秒,我需要把它转换成天,小时,分钟和秒。在
昨天晚上一直在挣扎。是的,你需要除法和模。不是最像Python的方式,但它对任何数量都有效,当你把你可以输入自动售货机的美元金额限制在5美元时。这个问题一直被问到,却一直被忽视。也许是因为它是家庭作业。。。不管怎样。。。。在
使用
divmod
,它只有三行:相关问题 更多 >
编程相关推荐