2008年6月24日 星期二

將字串型態的運算式,轉成真正的數學運算式

有時程式會用到外部傳入的運算式,
可是傳入的卻是字串型態,
這時可以用.NET 的 COM 元件來計算

Private Function CalculateEquation(ByVal strEquation As String) As Double
'要先引用 [Microsoft Script Control 1.0] 的 COM 元件
Dim MsScrCtl As New MSScriptControl.ScriptControl
MsScrCtl.Language = "VBSCript"
'傳回結果
Return sc.Eval(strNewEquation)
End Function

不過通常結果沒那麼簡單,大多數都是運算式中有很多值要替換,
因此可以將字串和值放入陣列中,

Public Class Form1

Private Structure typCalculateValue
Dim Name As String
Dim Value As Double
End Structure

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strValue(2) As typCalculateValue
strValue(0).Name = "TestA"
strValue(0).Value = 0.0894216
strValue(1).Name = "TestB"
strValue(1).Value = 0.0436392
strValue(1).Name = "TestC"
strValue(1).Value = 0.42
Dim strEquation As String
strEquation = "((TestA/2+(TestB*TestC)-123.456)/77)*(1e2)"
MsgBox(CalculateEquation(strValue, strEquation))
End Sub

Private Function CalculateEquation(ByVal aryTmpValue() As typCalculateValue, ByVal strEquation As String) As Double
'要先引用 [Microsoft Script Control 1.0] 的 COM 元件
Dim MsScrCtl As New MSScriptControl.ScriptControl
MsScrCtl.Language = "VBSCript"
Dim i As Integer
Dim strNewEquation As String
strNewEquation = strEquation
For i = 0 To UBound(aryTmpValue)
strNewEquation = Replace(strNewEquation, aryTmpValue(i).Name, aryTmpValue(i).Value)
Next
Return MsScrCtl.Eval(strNewEquation)
End Function
End Class

沒有留言:

張貼留言