2014-10-05 45 views
-5

但是,我意識到如果不檢查每種可能的硬幣組合,我都不知道如何自己做到這一點。必須有更好的方法來解決這個問題,但我不知道這種類型的算法的通用名稱會被調用,而且我無法找到一種方法來簡化它,除了查看每個解決方案之外。編寫一個Python程序,反覆要求用戶輸入硬幣值,直到總金額與目標值相匹配

我想知道是否有人能指引我朝着正確的方向發展,還是提出更高效的算法。

回答

0

你可以嘗試這樣的事情:

MaxAmount = 100 
TotalAmount = 0 

while TotalAmount < MaxAmount: 
    #Here if you want it to be more precise on decimals change int(raw_input("Amount: ")) to float(raw_input("Amount: ")) 
    EnteredAmount = float(raw_input("Amount: ")) 
    if EnteredAmount > MaxAmount: 
     print "You can not go over 100" 
    elif TotalAmount > MaxAmount: 
     #You can go two ways here either just set TotalAmount to MaxAmount or just cancel the input 
     print "You can not go over 100" 
    elif EnteredAmount <= MaxAmount: 
     TotalAmount = TotalAmount + EnteredAmount 
     print TotalAmount 
print "You have reached the total amount of ", MaxAmount 
+0

你可以看看另一個問題。這是鏈接http://stackoverflow.com/questions/26223346/write-a-python-program-that-repeatedly-asks-the-user-to-input-coin-values-until/26223797#26223797 – mmmmmm111 2014-10-06 21:30:54

0

可以使用循環進入if - elif - else語句 例如,填充一個變量與金額,然後使用此爲循環條件不斷地問拿走硬幣數量,直到你達到0

相關問題