金山区团区委书记:VB计算器差错

来源:百度文库 编辑:高考问答 时间:2024/05/06 01:24:57
下面是我刚写的一个计算器,好像除了加法都错了??我觉得是if那个语句的逻辑错误,怎么修正一下呢?谢谢
(是不是因为我的逻辑思维不好啊??)

Option Explicit
Dim x(4) As Double

Private Sub Command1_Click()
Text1.Text = Val(Val(Text1.Text) & Val(1))
End Sub

Private Sub Command10_Click()
Text1.Text = Val(Val(Text1.Text) & Val(0))
End Sub

Private Sub Command11_Click()
x(1) = Val(Text1.Text)
Text1.Text = Val(0)
End Sub

Private Sub Command12_Click()
x(2) = Val(Text1.Text)
Text1.Text = Val(0)
End Sub

Private Sub Command13_Click()
x(3) = Val(Text1.Text)
Text1.Text = Val(0)
End Sub

Private Sub Command14_Click()
x(4) = Val(Text1.Text)
Text1.Text = Val(0)
End Sub

Private Sub Command15_Click()
x(0) = Val(Text1.Text)
If Val(x(1)) <> Val(0) Then
Text1.Text = Val(Val(x(1)) + Val(x(0)))
ElseIf Val(x(2)) <> Val(0) Then
Text1.Text = Val(Val(x(2)) - Val(x(0)))
ElseIf Val(x(3)) <> Val(0) Then
Text1.Text = Val(Val(3) * Val(0))
ElseIf Val(x(4)) <> Val(0) Then
Text1.Text = Val(Val(4) / Val(0))
End If
End Sub

Private Sub Command16_Click()
Text1.Text = Val(0)
End Sub

Private Sub Command2_Click()
Text1.Text = Val(Val(Text1.Text) & Val(2))
End Sub

Private Sub Command3_Click()
Text1.Text = Val(Val(Text1.Text) & Val(3))
End Sub

Private Sub Command4_Click()
Text1.Text = Val(Val(Text1.Text) & Val(4))
End Sub

Private Sub Command5_Click()
Text1.Text = Val(Val(Text1.Text) & Val(5))
End Sub

Private Sub Command6_Click()
Text1.Text = Val(Val(Text1.Text) & Val(6))
End Sub

Private Sub Command7_Click()
Text1.Text = Val(Val(Text1.Text) & Val(7))
End Sub

Private Sub Command8_Click()
Text1.Text = Val(Val(Text1.Text) & Val(8))
End Sub

Private Sub Command9_Click()
Text1.Text = Val(Val(Text1.Text) & Val(9))
End Sub

Private Sub Text1_Change()
If Len(Text1.Text) > 20 Then
Text1.Text = Val(0)
MsgBox "溢出!原因:数据过大!", , "温馨提示--左兴东"
End If
End Sub

首先一点,你有频繁使用Val函数的坏习惯
如果你事先定义好变量类型,就不需要一直使用Val函数了

Private Sub Command15_Click()
x(0) = Val(Text1.Text)
If Val(x(1)) <> Val(0) Then
Text1.Text = Val(Val(x(1)) + Val(x(0)))
ElseIf Val(x(2)) <> Val(0) Then
Text1.Text = Val(Val(x(2)) - Val(x(0)))
ElseIf Val(x(3)) <> Val(0) Then
Text1.Text = Val(Val(3) * Val(0))
ElseIf Val(x(4)) <> Val(0) Then
Text1.Text = Val(Val(4) / Val(0))
End If
End Sub

这一段我觉得好奇怪,为什么要判断x(?)与x(0)的关系?而且如果x
(0)=0,那你在除法的地方就完蛋了。(已经完蛋了,自己看,是不是除以0啊?)

我对你的代码进行分析
发现Command11-14对应+-*/
但是Command16对应CE的代码你没有写清楚
至少要写成这个样子

Private Sub Command16_Click()
Text1.Text = Val(0)
x(1) = 0
x(2) = 0
x(3) = 0
x(4) = 0
End Sub

否则上次作加法,下次不管怎么样还是做加法

同样的,你要在Command15那里加上
Private Sub Command15_Click()
x(0) = Val(Text1.Text)
If Val(x(1)) <> 0 Then
Text1.Text = Val(Val(x(1)) + Val(x(0)))
ElseIf Val(x(2)) <> 0 Then
Text1.Text = Val(x(2)) - Val(x(0))
ElseIf Val(x(3)) <> Val(0) Then
Text1.Text = Val(3) * Val(x(0))
ElseIf Val(x(4)) <> Val(0) Then
Text1.Text = Val(4) / Val(x(0))
End If
x(1) = 0
x(2) = 0
x(3) = 0
x(4) = 0

End Sub

你可以试一试,应该可以了

好麻烦啊,我都不知道你的程序是想实现什么功能的。更严重的是,我看过了,用VB6.0看过了,好象没有运行错误的。