2015-10-21 118 views
2

我正在使用Python,并且我试图将美分的一定数量的钱转换为宿舍,镍,硬币和便士中的等价物。使用Python将美分转换为宿舍,镍币,硬币和便士

这是我到目前为止,但我看到的问题是,我不知道如何从宿舍拿走余下的钱,并将其分解为硬币,镍和便士。我对此很陌生,只是很难过。我并不是要求某人解决问题,只是指出我做错了什么(也许我需要做些什么才能解决问题)。

# 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) 
+0

您计算了'cents%quarter',但没有将它分配给下一个语句的变量。基于你有什么可以做'美分=美分%季度'。同样的'美分%'陈述的其余部分。 – metatoaster

+0

你也可以为此使用'divmod'。 –

回答

2

使用divmod,它只是三行:

quarters, cents = divmod(cents, 25) 
dimes, cents = divmod(cents, 10) 
nickels, pennies = divmod(cents, 5) 
0

还有,你在这里需要两个操作:整数除法

整数除法A/B问一个简单的问题:有多少次会B嵌入A干净(无需打破B成十进制件)? 2干净地适合84次。 2干净地适合94次。

A % B问同样的问题,但给出的答案的翻盖侧:鉴于A进入B干净一些的次数,什么遗留2毫无遗漏地进入84次,所以2 % 802干净地进入94次,但1被遗忘,因此2 % 91

我给你举另一个例子,让你从这个过渡到你的问题。比方说,我给了一些,我需要将其转换为小时分钟

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 
+0

谢谢dogwynn为你的帮助你的解释把它打破了恰到好处 – UchiaSky

+0

好,我很高兴。祝你好运,@DerekMcFarland。 – dogwynn