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

C#如何存储do-while循环中每次迭代的price值避免被覆盖

解决C#循环输入价格无法存储所有值的方案

你当前使用单个decimal变量存储输入值,每次迭代必然覆盖上一次的输入,改用集合类存储所有有效输入即可解决问题。

实现步骤

  • 在循环外声明List<decimal>类型的集合存储所有价格,代码顶部需要引入命名空间using System.Collections.Generic;
  • 每次输入完成后,判断值不是退出标记-1时,将其添加到集合中
  • 循环结束后可遍历集合读取所有存储的价格

修改后代码

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int count = 0;
        decimal price = 0;
        // 初始化集合存储价格
        List<decimal> allPrices = new List<decimal>();
        
        do
        {
            ++count;
            Console.Write("Item {0}", count);
            Console.Write("     Enter Price: $ ");
            price = Convert.ToDecimal(Console.ReadLine());
            
            // 仅存储非退出的有效值
            if (price != -1)
            {
                allPrices.Add(price);
            }
       
        } while (price != -1);
    }
}

优化建议

  • 用decimal.TryParse替代Convert.ToDecimal处理非法输入,避免用户输入非数字内容时程序抛出异常
  • 若提前知晓输入总数,也可使用decimal[]数组存储,动态输入场景下List<decimal>灵活度更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:18:01