餐饮点餐系统计算问题:同款不同规格商品总价不符
问题分析与解决方案
一、计算逻辑的错误点
total的计算逻辑完全错误
你当前代码中处理规格时的total计算逻辑是先加单价再乘以数量,比如:total = total + 50 total = total * i这会导致多次下单时总价错误增长。比如第一次买2份大份薯条,total从0变成50再乘2得100(此步结果碰巧正确),但第二次买2份中份时,total先变成100+35=135,再乘2变成270,而正确结果应该是100 + 35*2=170,这是两者结果不一致的核心原因。正确计算应该是直接加上「单价×数量」,即
total += 20 * i。fs/fm/fl未做累计,每次下单会覆盖之前的值
比如第一次买2份大份薯条,fl=250=100,之后再买1份大份,fl会被重置为150=50,之前的数量未被累加,这也会导致fs+fm+fl的结果与实际总金额不符。正确写法应该是fs += i *20,而非直接赋值。
二、更高效的规格商品总价计算方法
不要用单独变量存储每个规格的金额,改用结构化数据管理购物车,比如列表嵌套字典,每个条目记录商品名称、规格、数量、单价,后续计算总价、展示购物车都会更灵活,也方便扩展更多商品和规格。
优化后的示例代码
food_menu = { "2": { "name": "Fries", "sizes": { "S": 20, "M": 35, "L": 50 } } # 可继续添加汉堡、热狗等其他商品 } cart = [] total = 0 def menu(): print(" MENU") print("Code Description Size Price") for code, item in food_menu.items(): size_str = "/".join(item["sizes"].keys()) price_str = "/".join(map(str, item["sizes"].values())) print(f" {code} {item['name']} {size_str} {price_str}") menu() def ordering(): global total print("\nPlease select the CODE of the food you want to order") while True: order_code = input("Type the code you want to order:\n") if order_code not in food_menu: print("\nInvalid input. Please put only the CODE of the item\n") continue item = food_menu[order_code] print(f"\nYou have selected {item['name']}\n") size = input(f"What size do you want? {'/'.join(item['sizes'].keys())}: ").upper() if size not in item["sizes"]: print("Invalid size") continue quantity = int(input("Enter quantity: ")) unit_price = item["sizes"][size] subtotal = unit_price * quantity # 将商品加入购物车 cart.append({ "name": item["name"], "size": size, "quantity": quantity, "unit_price": unit_price, "subtotal": subtotal }) # 更新总价 total += subtotal print(f"Added {quantity}x {item['name']} ({size}) - {subtotal}") try_again = input("\nWould you like to add more? (Y/N):").lower() if try_again != "y": break def show_cart(): global total print('\n\nThe inside of your cart are currently:') for idx, item in enumerate(cart, 1): print(f"{idx}. {item['quantity']}x {item['name']} ({item['size']}) - {item['unit_price']} each, total: {item['subtotal']}") print(f"\nTotal amount: {total}") suggestion = input("Would you like to order more? Y/N: ").lower() if suggestion == "y": ordering() show_cart() ordering() show_cart()
优化点说明
- 用字典
food_menu统一管理商品信息,新增商品或规格只需修改该字典,扩展性极强 - 购物车
cart用列表存储每个下单条目,包含完整商品信息,方便后续查看、修改或计算 - 总价计算直接累加每个条目的小计,逻辑清晰,不会出错
- 代码结构更模块化,后续添加支付、修改订单等功能更便捷
内容的提问来源于stack exchange,提问作者morkie
相关产品推荐
相关产品推荐

