{S0}简介
这是另一个数学表达式计算器,使用它可以让用户键入文本格式的表达与三个变量(X,Y,Z),并根据计算的结果变量值。其主要思想
解析文本的功能,并建立一个树状结构,因为数学表达式始终是一个经营者与quot; somethingquot;左和quot; somethingquot;权。"somethingquot;可以是一个变量或一个数字或表达式本身。罪等功能,COS ...特殊的节点,其参数是一个表达式。很简单,是不是?
例如:2 * X - 4/sin(3 * X)根据操作的优先级是一个减法,如果我们建立这样的一棵树... ... -----
| - |
-----
_______| | |_______
| ----- |
----- -----
| * | | / |
----- -----
_| | |_ _| | |_
| ----- | | ----- |
----- ----- ----- -----
| 2 | | X | | 4 | | sin |
| nr. | | var | | nr. | |-----|
----- ----- ----- | |
--|--
|
-----
| * |
-----
_| | |_
| ----- |
----- -----
| 3 | | X |
| nr. | | var |
----- -----
...从左至右扫描树,我们可以读出原始的表达。建筑树
每个节点类型(操作员,操作数,函数)实施适当的类。{C}
我们构建表达式树的运算符优先级这样:函数表达式处理分右左总结|调用的每边的功能任期。功能项处理左MULT |格的权利要求每一方的功能因子。功能因子处理遗留下来的权力的权利,呼吁每边的功能电源。功能电源检测到一个新的表达式(如括号),功能(3个字母),变量,或数字结束工作。
计算结果
一旦我们有树,扫描从左至右计算的结果是相当简单:Protected Overridable Function GetResult(ByVal objNode As Object) As Decimal
'calculate the result of the function in terms of x,y,z
'by recursively scanning the tree from left to right
If objNode Is Nothing Then Return 0
If TypeOf objNode Is clsFunction Then
Select Case objNode.Name.ToLower
Case "sin"
Return System.Math.Sin(GetResult(objNode.Argument))
Case "cos"
Return System.Math.Cos(GetResult(objNode.Argument))
Case "tan"
Return System.Math.Tan(GetResult(objNode.Argument))
Case "atn"
Return System.Math.Atan(GetResult(objNode.Argument))
Case "lne"
Return System.Math.Log(GetResult(objNode.Argument))
Case "log"
Return System.Math.Log10(GetResult(objNode.Argument))
Case "sqr"
Return System.Math.Sqrt(GetResult(objNode.Argument))
End Select
ElseIf TypeOf objNode Is clsOperator Then
Select Case objNode.operator
Case "+"
Return GetResult(objNode.Left) + GetResult(objNode.Right)
Case "-"
Return GetResult(objNode.Left) - GetResult(objNode.Right)
Case "*"
Return GetResult(objNode.Left) * GetResult(objNode.Right)
Case "/"
Return GetResult(objNode.Left) / GetResult(objNode.Right)
Case "^"
Return GetResult(objNode.Left) ^ GetResult(objNode.Right)
End Select
ElseIf objNode.isvariable Then
Select Case objNode.variable
Case "X"
Return mX
Case "Y"
Return mY
Case "Z"
Return mZ
End Select
Else
Return objNode.operand
End If
End Function
的源代码,为更多的评论。使用代码dim LtFn as New LTFunctions.Functions
With LtFn
.Function = "sin(x)+2*p"
.X =-1
.Y = 0
.Z = 0
Messagebox.Show (Format(.Result, "standard"))
End With