菲波那切数列的第一项是1,第二项是1,其后各项都是前两项之和,试用递归算法和非递归算法各编写一个程序
收起
知与谁同
2018-07-19 15:15:47
2030
0
1
条回答
写回答
取消
提交回答
-
'递归函数
Public Function fb(n As Integer) As Single
If n > 2 Then
fb = fb(n - 1) + fb(n - 2)
Else
If n = 2 Then
fb = 1
Else
If n = 1 Then
fb = 1
Else
fb = 0
End If
End If
End If
End Function
'非递归
Dim a As Single, b As Single, c As Single, n As Integer
a = 1
b = 1
n = Val(InputBox("输入n"))
'打印递归函数值
Print fb(n)
’以下为非递归算法
If n > 2 Then
For i = 3 To n Step 1
c = a + b
a = b
b = c
Next i
Else
If n = 1 Then
c = 1
Else
If n = 2 Then
c = 1
End If
End If
End If
Print c
2019-07-17 22:55:43