逆波兰式(http://baike.baidu.com/view/2582.htm)
vb.net实现如下:
Public Class Form1 Dim S As New Stack Dim R As New Stack Public Function Calc(ByVal StrIn As String) As String Dim ch() As String Dim x As Single Dim i As Integer ch = Split(StrIn," ") For i = 0 To UBound(ch) Select Case ch(i) Case "+" : x = S.Pop + S.Pop Case "-" : x = S.Pop : x = S.Pop - x Case "*" : x = S.Pop * S.Pop Case "/" x = S.Pop If x <> "0" Then x = S.Pop / x Else MsgBox("被零除,出错!") End If Case Else x = CSng(ch(i)) End Select S.Push(x) Next If S.Count = 1 Then Calc = S.Pop Else MsgBox("表达式出错了!") End If End Function Public Sub Change(ByVal StrIn As String,ByRef StrOut As String) '生成逆波兰式 'Dim R As New ClsStack Dim i As Integer,j As Integer Dim ch As String,w As String R.Push("@") i = 0 : j = 0 ch = Microsoft.VisualBasic.Left(StrIn,1) Dim k As Integer Dim sTmp As String k = 2 Do While ch <> "" Select Case ch Case "" : Exit Do Case " " Case "(" : R.Push(ch) Case ")" sTmp = R.Pop Do While sTmp <> "(" StrOut = StrOut & sTmp & " " sTmp = R.Pop Loop Case "+","-","*","/" w = R.Peek Do While Prec(w) >= Prec(ch) StrOut = StrOut & w & " " R.Pop() : w = R.Peek Loop R.Push(ch) Case Else Do While IsNumeric(ch) Or ch = "." StrOut = StrOut & ch ch = Mid(StrIn,k,1) : k = k + 1 Loop StrOut = StrOut & " " : k = k - 1 End Select ch = Mid(StrIn,1) : k = k + 1 Loop ch = R.Pop Do While ch <> "@" If ch = "(" Then MsgBox("表达式不正确,请检查!") StrOut = StrOut & ch & " " ch = R.Pop Loop StrOut = Microsoft.VisualBasic.Left(StrOut,Len(StrOut) - 1) End Sub Private Function Prec(ByVal op As String) As Integer '操作符的优先级别 Select Case op Case "+","-" : Prec = 1 Case "*","/" : Prec = 2 Case "@" : Prec = -1 Case "(" : Prec = 0 End Select End Function Private Sub Okbtn_Click(ByVal sender As Object,ByVal e As System.EventArgs) Handles Okbtn.Click Change(TextBox1.Text,TextBox2.Text) TextBox2.Text = Calc(TextBox2.Text) End Sub End Class