怎样用VB语言解决斐波拉契数列相加问题?

来源:百度知道 编辑:UC知道 时间:2024/07/07 06:22:14
比如:求1+2+3+5+8+13+21+...+n

求1+2+3+5+8+13+21+...+n和的函数如下:
参数n为最后一项n
Private Function fun(n As Integer) As Long
Dim a, b, c, d As Long
If n <= 2 Then
fun = n
Exit Function
End If
a = 1: b = 2: d = 3
Do
c = a + b
n = n - c
d = d + c
a = b
b = c
Loop While n > 0
fun = d
End Function
参数n为总项数:
Private Function fun(n As Integer) As Long
Dim a, b, c, d As Long
If n <= 2 Then
fun = n
Exit Function
End If
a = 1: b = 2: d = 3: n = n - 2
Do
c = a + b
n = n - 1
d = d + c
a = b
b = c
Loop While n > 0
fun = d
End Function