如何修复VB简单计算器中“参数'Expression'无法转换为'RadioButton'类型”错误
错误原因
- 所有
Val(radAdd) = True这类判断逻辑写法错误:radAdd是单选按钮(RadioButton)控件对象,你直接将控件传入用于转换数值的Val()函数,类型不匹配触发报错。判断单选按钮是否被选中,直接读取控件的Checked布尔属性即可,不需要套Val()。 - 代码还存在几处隐性问题:
- 求最小值的分支逻辑错误,Else分支错误返回了第一个输入框的值,应该返回第二个输入框的值
Math.Pow返回值为Double类型,直接赋值给Integer类型变量可能出现精度丢失或溢出- 未做除零判断,选中除法时如果第二个输入框为0会触发运行时错误
- 未提前校验输入内容是否为有效数字,输入非数字内容时会报错
修正后代码
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCal.Click ' 先校验输入是否为有效数字 If Not IsNumeric(txtIn1.Text) Or Not IsNumeric(txtIn2.Text) Then txtResult.Text = "Invalid input" Exit Sub End If Dim num1 As Double = Val(txtIn1.Text) Dim num2 As Double = Val(txtIn2.Text) If radAdd.Checked Then txtResult.Text = (num1 + num2).ToString() ElseIf radSub.Checked Then txtResult.Text = (num1 - num2).ToString() ElseIf radMul.Checked Then txtResult.Text = (num1 * num2).ToString() ElseIf radDiv.Checked Then If num2 = 0 Then txtResult.Text = "Cannot divide by zero" Else txtResult.Text = (num1 / num2).ToString() End If ElseIf radRem.Checked Then txtResult.Text = (num1 Mod num2).ToString() ElseIf radexp.Checked Then txtResult.Text = Math.Pow(num1, num2).ToString() ElseIf radMax.Checked Then txtResult.Text = Math.Max(num1, num2).ToString() ElseIf radmin.Checked Then txtResult.Text = Math.Min(num1, num2).ToString() Else txtResult.Text = "Please select an operation" End If End Sub
内容的提问来源于stack exchange,提问作者Wohan Chamara
相关产品推荐
相关产品推荐

