擅长:python、mysql、java
<p>你只需要把你在每一步所做的改变减去你在每一步所做的改变。如果将变量名更改为有意义的名称,则更容易查看:</p>
<pre><code>price= int(raw_input('price: ')) # Use int(raw_input()) for safety.
paid= int(raw_input('cash paid: '))
coin_bills=[100,50,20,10,5,1,0.5]
if paid >= price:
change = paid - price
for i in coin_bills:
# Use // to force integer division - not needed in Py2, but good practice
# This means you can't give change in a size less than the smallest coin!
print (change // i),'*',i
change -= (change // i) * i # Subtract what you returned from the total change.
else:
print 'pay up!'
</code></pre>
<p>您还可以通过只打印实际返回的硬币/钞票来清除输出。那么内部循环可能看起来像这样:</p>
<pre><code>for i in coin_bills:
coins_or_bills_returned = change // i
if coins_or_bills_returned: # Only print if there's something worth saying.
print coins_or_bills_returned,'*',i
change -= coins_or_bills_returned * i
</code></pre>