|
VB中文本框一般用于字符串的输入或输出。如果我们在文本框中输入(21+32)*43-((5+6-8)/2+10)*2,你是否希望它能自动计算出结果?以下程序是实现这一功能的全部代码。打开VB新建一工程,在Form1上添加一Text控件,拉长一点,以便输入四则表达式和输出结果,复制以下代码。运行程序后在文本框中输入任意的四则运算式,回车。看看结果如何。
Dim val_Str() As String
Dim Resu As Double
Dim iP_N() As Integer '用于判断数据的正负
Dim sSt() As String * 1
Dim Kuohao() As Integer
Function calc_Kuohao(str_tex As String) As Double '括号计算
Dim text_strr As String
Dim mm_stR As String
text_strr = Trim(str_tex)
i_len = Len(text_strr)
aa = Mid(text_strr, 1, 1)
If aa = "-" Or aa = "+" Or aa = "*" Or aa = "/" Then Str_Text1 = "0" & text_strr
ii = 0
For i = 1 To i_len '判断括号是否成对
mm_stR = Mid(text_strr, i, 1)
If mm_stR = "(" Then ii = ii + 1
If mm_stR = ")" Then ii = ii - 1
If ii < 0 Then
MsgBox ("括号不成对")
Exit Function
End If
Next
If ii <> 0 Then '
MsgBox ("括号不成对")
Exit Function
End If
If InStr(1, text_strr, "(") > 0 Then '如果有括号,现按最里层括号计算
ReDim sSt(1 To Len(text_strr))
ReDim Kuohao(1 To Len(text_strr))
Do While True
i_len = Len(Trim(text_strr))
ceng = 1
For i = 1 To i_len
sSt(i) = Mid(text_strr, i, 1)
Next
If InStr(1, text_strr, "(") <> 0 And InStr(1, text_strr, "(") <> 0 Then '计算有多少对括号,不成对返回0
text_strr = ""
For i = 1 To i_len '判断括号是否为0
text_strr = text_strr & sSt(i)
Next
For i = 1 To i_len
Kuohao(i) = 0 '清零
If sSt(i) = "(" Then
Kuohao(i) = ceng
ceng = ceng + 1
End If
If sSt(i) = ")" Then
ceng = ceng - 1
Kuohao(i) = ceng
End If
Next
zuiD = 0: id = 1
For i = 1 To i_len '求最内层括号
If Kuohao(i) > zuiD Then
zuiD = Kuohao(i)
id = i
End If
Next 'kuohao(iD)最内层
mm = InStr(id, text_strr, ")")
If mm <> 0 Then 'mm=")"
mm_stR = Mid(text_strr, id + 1, mm - id - 1)
resu_str = cacul_Str(mm_stR) '计算
text_strr = Mid(text_strr, 1, id - 1) & resu_str & Mid(text_strr, mm + 1, i_len - mm)
Else
Exit Do
End If
上一篇:随心所欲修改Winamp播放清单
下一篇:FlashFXP使下载速度快两倍
|