2015-10-21 43 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