VBA梯形积分方法

时间:2015-10-18 12:10:17

标签: vba

我的函数为1500/(1+x*.0042),从0到950集成,我用梯形方法。 n指的是梯形的数量。我的功能没有得到任何输出。如果可以,请帮忙。

Function TotalArea(n As Double) As Double
    Dim a As Double
    Dim b As Double
    Dim dx As Double
    Dim i As Double
    a = 0
    b = 950
    dx = (b - a) / n
    TotalArea = 0
    For i = 0 To 950 Step dx
     TotalArea = TotalArea + (((1500 / (1 + i * 0.0042) + 1500 / (1 + (i + dx) * 0.0042))))
    Next i
    TotalArea = TotalArea / 2
End Function

1 个答案:

答案 0 :(得分:0)

将函数名称用作函数中的变量并不是一个好习惯,但是您的代码确实会返回值。

您可能需要考虑以下(数学简化):

Option Explicit

Function TotalArea(n As Double) As Double
    Const k As Double = 1500
    Const r As Double = 0.0042

    Dim a As Double
    Dim b As Double
    Dim dx As Double
    Dim i As Double
    Dim Area As Double

    a = 0
    b = 950
    dx = (b - a) / n
    Area = 0
    For i = a To b Step dx
        Debug.Print "i: " & i & " (dx: " & dx & ", Area: " & Area & ")"
        Area = Area + ((1 / (1 + i * r) + 1 / (1 + (i + dx) * r)))
    Next i
    TotalArea = k * Area / 2
End Function