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
相关产品推荐
相关产品推荐

