如何在C#的while循环中持续为float变量累加数值?
问题解决:硬币收藏累加失效的原因及修复
你的代码里硬币无法累加的核心问题是复合赋值运算符写反了:
- 你写的
collection =+ add实际是把+add(也就是add本身)赋值给collection,而非累加 - 正确的累加运算符是
+=,同理递减应该用-=而不是=-
修正后的完整代码
// 硬币是整数单位,用int更合理 int add, take, collection; collection = 0; bool on = true; while (on) { Console.WriteLine("查看收藏请按1"); Console.WriteLine("添加硬币请按2"); Console.WriteLine("取出硬币请按3"); string choice = Console.ReadLine(); switch (choice) { case "1": Console.WriteLine("你现在有 " + collection + " 枚硬币"); Console.Write("要回到菜单请按K,否则退出:"); string str = Console.ReadLine(); if (str != "K") { on = false; } break; case "2": Console.Write("要添加多少枚硬币?:"); string str1 = Console.ReadLine(); // 增加输入验证,避免非数字输入导致崩溃 if (int.TryParse(str1, out add)) { collection += add; Console.WriteLine("你现在的收藏有 " + collection + " 枚硬币"); } else { Console.WriteLine("请输入有效的数字!"); } Console.Write("要回到菜单请按K,否则退出:"); string str2 = Console.ReadLine(); if (str2 != "K") { on = false; } break; case "3": Console.Write("要取出多少枚硬币?:"); string str3 = Console.ReadLine(); if (int.TryParse(str3, out take)) { // 防止取出数量超过现有收藏,避免出现负数 if (take <= collection) { collection -= take; Console.WriteLine("你现在的收藏有 " + collection + " 枚硬币"); } else { Console.WriteLine("你没有足够的硬币可以取出!"); } } else { Console.WriteLine("请输入有效的数字!"); } Console.Write("要回到菜单请按K,否则退出:"); string str4 = Console.ReadLine(); if (str4 != "K") { on = false; } break; default: Console.WriteLine("请输入正确的选项(1/2/3)"); break; } }
额外优化说明
- 类型调整:硬币数量是整数,用
int替代float,避免浮点数精度问题 - 输入防护:用
int.TryParse做输入验证,防止用户输入非数字导致程序崩溃 - 边界校验:取出硬币时检查数量是否合理,避免出现负数硬币
- 错误处理:switch添加default分支,处理用户输入错误选项的情况
内容的提问来源于stack exchange,提问作者200cansofcatfood
相关产品推荐
相关产品推荐

