逆波兰表达式在VB中编程???

lihuanmei 2008-12-19 01:03:04
Problem :逆波兰表达式

逆波兰表达式是一种把运算符前置的算术表达式,例如普通的表达式2 + 3的逆波兰表示法为+ 2 3。逆波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如(2 + 3) * 4的逆波兰表示法为* + 2 3 4。本题求解逆波兰表达式的值,其中运算符包括+ - * /四个。
输入为一行,其中运算符和运算数之间都用空格分隔,运算数是浮点数。
输出为一行,表达式的值。
可直接用printf("%f\n", v)输出表达式的值v。
可使用atof(str)把字符串转换为一个double类型的浮点数。atof定义在math.h中。
此题可使用函数递归调用的方法求解。


请问各位大侠:如何编程啊??
...全文
151 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zzyong00 2008-12-20
  • 打赏
  • 举报
回复
Dim symbol() As String, data() As String

Private Sub Command1_Click()
ReDim symbol(0), data(0)
Dim s As String
Analysis " / * + 2 3 4 5"
Debug.Print Calc(s)
End Sub

Public Function Analysis(ByVal exp As String) As String
Dim strCh As String
Dim i As Integer
For i = 1 To Len(exp)
strCh = Mid$(exp, i, 1)
If strCh <> " " Then
If strCh = "+" Or strCh = "-" Or strCh = "*" Or strCh = "/" Then
symbol(UBound(symbol)) = strCh
ReDim Preserve symbol(UBound(symbol) + 1)
ElseIf IsNumeric(strCh) Then
data(UBound(data)) = strCh
ReDim Preserve data(UBound(data) + 1)
Else
Analysis = "error"
End If
End If
Next
End Function

Public Function Calc(ByVal ErrMsg As String) As Double
On Error GoTo ToExit '´ò¿ª´íÎóÏÝÚå
'------------------------------------------------
Dim i As Integer, intPos As Integer
Dim result As Double
For i = UBound(symbol) - 1 To 0 Step -1
Select Case symbol(i)

Case "+"
If pos = 0 Then
result = Val(data(pos)) + Val(data(pos + 1))
pos = pos + 1
Else
result = result + Val(data(pos + 1))
pos = pos + 1
End If
Case "-"
If pos = 0 Then
result = Val(data(pos)) - Val(data(pos + 1))
pos = pos + 1
Else
result = result - Val(data(pos + 1))
pos = pos + 1
End If
Case "*"
If pos = 0 Then
result = Val(data(pos)) * Val(data(pos + 1))
pos = pos + 1
Else
result = result * Val(data(pos + 1))
pos = pos + 1
End If
Case "/"
If pos = 0 Then
result = Val(data(pos)) / Val(data(pos + 1))
pos = pos + 1
Else
result = result / Val(data(pos + 1))
pos = pos + 1
End If
End Select
Next
Calc = result
'------------------------------------------------
Exit Function
'----------------
ToExit:
ErrMsg = Err.Number & ":" & Err.Description
End Function
mokton 2008-12-20
  • 打赏
  • 举报
回复
学习呀
Tiger_Zhao 2008-12-19
  • 打赏
  • 举报
回复

sub main()
debug.print f("*+234",1)
end sub
function f(byval exp as string, byref i as long) as double
dim ch as string, a as double, b as double
ch = mid$(exp,i,1)
i = i+1
select case ch
case "+"
a = f(exp, i)
b = f(exp, i)
f = a + b
case "-" '参考 case "+"
case "*" '参考 case "+"
case "/" '参考 case "+"
case else
f = val(ch)
end select
end function

7,787

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧