将数据库中的字符串转成公式的算法(原创)

最近由于开发需要,需要编写将数据库中的字符串转化为公式并计算出结果的程序,在网上找了一些资料,很少呀,无奈只有自己动手开刀了,由于是分段函数,所以数据库中的字符串要含有变量的取值范围,要把这些取值范围取出来,对应于相应的函数。

思路是这样的,在数据库存放带格式的公式串,例如“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 ,所以实现起来简单多了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值