最近由于开发需要,需要编写将数据库中的字符串转化为公式并计算出结果的程序,在网上找了一些资料,很少呀,无奈只有自己动手开刀了,由于是分段函数,所以数据库中的字符串要含有变量的取值范围,要把这些取值范围取出来,对应于相应的函数。
思路是这样的,在数据库存放带格式的公式串,例如“0,4;0.75*x+12|5,10;0.6*x+10|11,~;0.4*x+12”,其中“|”作为公式段的分隔符号,前面两个数字即为变量的取值范围,用split函数将字符串分隔好,然后取出即可。
Function ConvertToFormula(ByVal strFormula As String, ByVal Value As Integer) As Decimal
'strFormula = "0,4;0.75*x+12|5,10;0.6*x+10|11,~;0.4*x+12"
Dim mscFormula As New MSScriptControl.ScriptControl '引用MS Script Control
Dim strArray(), strArray1() As String
Dim strTemp1, s, s1(), s2 As String
Dim decResult As Decimal
Dim i, demension As Integer
mscFormula.Language = "vbscript"
'strFormula = "0,4;0.75*x+12|5,10;0.6*x+10|11,~;0.4*x+12"
If strFormula <> "" Then
strArray = strFormula.Split("|") '取得"0,4;0.75*x+12"
demension = strArray.GetUpperBound(0)
Dim strFm(demension), x1(demension), x2(demension) As String
For i = 0 To strArray.GetUpperBound(0) - 1
strTemp1 = strArray(i).ToString
strArray1 = strTemp1.Split(";") '取得"0,4"
s1 = strArray1(0).Split(",") 'Get 0 and 4
s2 = strArray1(1).ToString 'Get "0.75*x+12"
x1(i) = s1(0).ToString 'get 0
x2(i) = s1(1).ToString 'get 4
If x2(i) = "~" Then
x2(i) = 10000
End If
strFm(i) = s2.ToString 'get "0.75*x+12"
Next
For i = 0 To strArray.GetUpperBound(0) - 1
If x1(i) <= Value <= x2(i) Then
s = strFm(i)
s = Replace(s, "x", Value)
decResult = mscFormula.Eval(s)
End If
Next
End If
Return decResult
End Function
算法中用到了MS Script Control ,所以实现起来简单多了。