def calculate_change(total_cost):
# 確保N <= 1000
if total_cost > 1000:
return "購買金額超過一千元,無法使用此程式計算找零。"
# 可用的零錢單位
denominations = [500, 100, 50, 10, 5, 1]
# 計算需要找回的總零錢
change_to_return = 1000 - total_cost
# 用來儲存各零錢單位數量的字典
change_count = {}
for denomination in denominations:
# 計算每個單位的零錢數量,並從總額中扣除相應的金額
count, change_to_return = divmod(change_to_return, denomination)
change_count[denomination] = count
return change_count
# 從用戶接收輸入
total_cost = int(input("顧客購買金額(N元):"))
# 計算找零
change = calculate_change(total_cost)
# 輸出找零結果
if isinstance(change, dict):
print("找回的零錢為:")
for denomination, count in change.items():
if count > 0:
print(f"{denomination}元:{count}張")
else:
print(change)
這段程式碼首先確認顧客購買的金額不超過一千元,然後計算需要找回的零錢總額。接著,它遍歷所有可能的零錢單位,使用 divmod 函數計算每種單位的數量以及剩餘需要找回的金額。最後,它會顯示出每種零錢單位應該找回多少張。
此程式可以幫助收銀員快速計算並以最少的零錢數量找回給顧客,減少等待時間並提高工作效率。