You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现循环用户输入、累加所选商品总价的程序开发求助

C# 循环商品订单累加总价程序实现

修改后的完整代码

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 初始化商品菜单字典(支持不区分大小写匹配)
        Dictionary<string, double> FoodMenu = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase)
        {
            {"Baja Taco", 4.00},
            {"Burrito", 7.50},
            {"Bowl", 8.50},
            {"Nachos", 11.00},
            {"Quesadilla", 8.50},
            {"Super Burrito", 8.50},
            {"Super Quesadilla", 9.50},
            {"Taco", 3.00},
            {"Tortilla Salad", 8.00}
        };

        double total = 0; // 用于累加订单总价

        while (true)
        {
            Console.WriteLine("Item:");
            string input = Console.ReadLine()?.Trim() ?? string.Empty;

            // 识别任意大小写的"End"指令,终止循环并输出最终总价
            if (string.Equals(input, "End", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine($"最终总价: ${total:F2}");
                break;
            }

            // 查找商品并累加价格
            if (FoodMenu.TryGetValue(input, out double price))
            {
                total += price;
                Console.WriteLine($"当前总价: ${total:F2}");
            }
            else
            {
                Console.WriteLine($"{input} 不在菜单中,请重新输入。");
            }
        }
    }
}

关键修改说明

  • 循环机制:用while(true)实现持续输入,直到触发终止条件。
  • 不区分大小写匹配:
    • 字典初始化时传入StringComparer.OrdinalIgnoreCase,用户输入小写/大写商品名都能匹配。
    • 用string.Equals的忽略大小写比较规则,识别end/END/End等所有终止指令。
  • 总价累加:新增total变量,每次找到有效商品后累加价格,用F2格式符保证输出两位小数的金额格式。
  • 输入健壮性:处理空输入或null值,避免程序抛出异常。
  • 高效查找:用TryGetValue替代ContainsKey+索引访问,一次操作完成存在性检查和取值,性能更优。

原代码的核心问题

  1. 无循环逻辑,仅支持单次输入。
  2. 缺少总价累加变量,无法计算多次订单总和。
  3. 匹配规则大小写敏感,用户输入容错性差。
  4. 静态方法调用和代码结构存在潜在的上下文问题。

内容的提问来源于stack exchange,提问作者GG45Gold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:26:06