自动售货机代码问题:如何实现找零计算?
VB.NET自动售货机找零计算问题排查与修复
问题分析
你的代码存在几个关键问题导致找零计算异常:
- 变量类型不匹配:
amount和change被定义为Integer(整数类型),但金额涉及小数(如0.6英镑),整数无法存储小数,直接赋值或计算会引发类型错误,同时丢失精度。 - 输入未做类型转换:
Console.ReadLine()返回的是字符串,直接赋值给数值类型变量会抛出转换异常,必须显式转换为合适的数值类型。 - 未输出找零结果:计算出
change后没有通过Console.WriteLine()输出,导致看不到最终找零。 - 冗余代码:重复输出了两次
option 3,属于笔误。
修正后的完整代码
Dim choice As String Dim amount As Decimal Dim change As Decimal Sub Main(args As String()) Console.WriteLine("option 1: snickers price = 60p") Console.WriteLine("option 2: coke price = £1") Console.WriteLine("option 3") Console.WriteLine("option 4") Console.WriteLine("option 5") Console.WriteLine("option 6") Console.WriteLine("option 7") Console.WriteLine("option 8") Console.WriteLine("option 9") Console.WriteLine("option 10") choice = Console.ReadLine() Select Case choice Case "1" Console.WriteLine("enter amount") ' 处理输入转换,避免非数字输入报错 If Decimal.TryParse(Console.ReadLine(), amount) Then If amount < 0.6D Then Console.WriteLine("not enough") Else change = amount - 0.6D Console.WriteLine($"Change: £{change.ToString("F2")}") End If Else Console.WriteLine("Invalid amount entered") End If Case "2" Console.WriteLine("enter amount") If Decimal.TryParse(Console.ReadLine(), amount) Then If amount < 1D Then Console.WriteLine("not enough") Else change = amount - 1D Console.WriteLine($"Change: £{change.ToString("F2")}") End If Else Console.WriteLine("Invalid amount entered") End If Case Else Console.WriteLine("Invalid option selected") End Select Console.ReadLine() End Sub
关键修改点说明
- 将
amount和change改为Decimal类型,适合处理货币计算,避免浮点数精度丢失问题。 - 使用
Decimal.TryParse()处理输入转换,同时验证输入是否为有效数字,防止程序崩溃。 - 添加找零结果输出,用
ToString("F2")格式化保留两位小数,符合货币显示规范。 - 修复重复的
option 3,添加默认分支处理无效选项。
内容的提问来源于stack exchange,提问作者qwer
相关产品推荐
相关产品推荐

