我正在使用Python,而我正在努力将一定数量的美分兑换成相当于季度,镍币,硬币和硬币的等价物。
这是我到目前为止所做的,但我发现问题在于我不知道如何从宿舍中取出剩余部分并将其分解为硬币,镍币和硬币。我是新手,只是很难过。我没有要求有人解决问题,只是指出我做错了什么(也许我需要做些什么来解决它)。
<form action="yourform.asp" novalidate>
答案 0 :(得分:2)
使用divmod
,它只有三行:
quarters, cents = divmod(cents, 25)
dimes, cents = divmod(cents, 10)
nickels, pennies = divmod(cents, 5)
答案 1 :(得分:0)
这里有两个操作:整数除法和模数。
整数除法A / B
提出一个简单的问题:B
干净地适合A
多少次(不必将B
分成小数部分)? 2
完全适合8
次4
次。 2
也适合9
4
次。
Modulo A % B
提出了同样的问题,但给出了答案的另一面:鉴于A
干净地进入B
多次,遗留下来的< / em>的? 2
8
干净地进入4
次,没有任何遗留,因此2 % 8
为0
。 2
9
干净地进入4
次,但1
仍然遗留,因此2 % 9
为1
。
我会给你另一个例子,让你从那个过渡到你的问题。假设我有一些秒,我需要将其转换为天,小时,分钟和秒。
total_seconds = 345169
# Specify conversion between seconds and minutes, hours and days
seconds_per_minute = 60
seconds_per_hour = 3600 # (60 * 60)
seconds_per_day = 86400 # (3600 * 24)
# First, we pull out the day-sized chunks of seconds from the total
# number of seconds
days = total_seconds / seconds_per_day
# days = total_seconds // seconds_per_day # Python3
# Then we use the modulo (or remainder) operation to get the number of
# seconds left over after removing the day-sized chunks
seconds_left_over = total_seconds % seconds_per_day
# Next we pull out the hour-sized chunks of seconds from the number of
# seconds left over from removing the day-sized chunks
hours = seconds_left_over / seconds_per_hour
# hours = seconds // seconds_per_hour # Python3
# Use modulo to find out how many seconds are left after pulling out
# hours
seconds_left_over = seconds_left_over % seconds_per_hour
# Pull out the minute-sized chunks
minutes = seconds_left_over / seconds_per_minute
# minutes = seconds_left_over // seconds_per_minute # Python3
# Find out how many seconds are left
seconds_left_over = seconds_left_over % seconds_per_minute
# Because we've removed all the days, hours and minutes, all we have
# left over are seconds
seconds = seconds_left_over
答案 2 :(得分:0)
昨天晚上正为此苦苦挣扎。确实,您需要除法和取模。这不是最Python的方式,但是它适用于任何金额,当您将可以输入自动售货机的金额限制为$ 5.00时,该金额就无效。这个问题被问到了,并一直被忽略。也许是因为它是家常便饭...无论如何...
def vending_machine_change():
cost = float(input("Enter cost of item: "))
change= 5.00-cost
dollars = int(change)
quarters_change= float("%.2f" % ((change-dollars)))
quarters =int(quarters_change/0.25)
dime_change= float("%.2f" % (quarters_change%0.25))
dimes=int(dime_change/0.10)
nickel_change = float("%.2f" % (dime_change%0.10))
nickels= int(nickel_change/0.05)
pennys = int(nickel_change*100)
print("Change amount: " + str((dollars)) + ' Dollars, ' + str((quarters)) + ' Quarters, '+ str((dimes)) + ' Dimes, '+ str((nickels)) + ' Nickels, '+ str((pennys)) + ' Pennies' )
pass