菲波那切数列的第一项是1,第二项是1,其后各项都是前两项之和,试用递归算法和非递归算法各编写一个程序
答案:1 悬赏:10 手机版
解决时间 2021-02-15 02:33
- 提问者网友:却不属于对方
- 2021-02-14 06:31
求菲波那切数列的前n项的值vb程序
最佳答案
- 五星知识达人网友:逐風
- 2021-02-14 07:00
'递归函数
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
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
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯