阿摩線上測驗 登入

申論題資訊

試卷:97年 - 097年身心障礙人員4等_資訊處理#37700
科目:程式設計
年份:97年
排序:0

申論題內容

三、請寫一程式可幫助收銀員找零錢給顧客。(20 分) 假設: ⑴顧客買了 N 元,給了收銀員一張千元紙鈔;此程式會提示收銀員該以最少數量之 零錢找回給顧客。 ⑵ N <= 1000。 ⑶可找回零錢之幣值單位為:500, 100, 50, 10, 5, 1 共六種

詳解 (共 1 筆)

詳解 提供者:hchungw
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 函數計算每種單位的數量以及剩餘需要找回的金額。最後,它會顯示出每種零錢單位應該找回多少張。
此程式可以幫助收銀員快速計算並以最少的零錢數量找回給顧客,減少等待時間並提高工作效率。