vb 關於自訂函數題目的問題?

2016-10-05 12:17 pm
想請可為高手幫忙解答下面這題

下列程式執行後,value得值為何?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim value As Integer
value = fibonacci(10)
MsgBox(value)
End Sub

Private Function fibonacci(ByVal n) As Integer
If n = 0 Then
fibonacci = 0
ElseIf n = 1 Then
fibonacci = 1
Else
fibonacci = fibonacci(n - 1) + fibonacci(n - 2)

End If
End Function
End Class
==========
麻煩給我詳解謝謝!
更新1:

補上選項 (A)21 (B)34 (C)55 (D)89

回答 (1)

2016-10-06 11:30 am
✔ 最佳答案
此題為著名的 Fibonacci 數列,
在數學上屬於"離散數學"中, "遞迴數列"的章節.
令 An 表示此數列的第 n 項,
其定義為:
A0 = 0
A1 = 1
An = An-1 + An-2 , for n ≧ 2
也就是, 第 0 項為 0 , 第 1 項為 1 , 之後的第 n 項為前兩項之和.

題目要求第 10 項, 也就是 A10 , 需逐項算出 :
A2 = A1 + A0 = 1 + 0 = 1
A3 = A2 + A1 = 1 + 1 = 2
A4 = A3 + A2 = 2 + 1 = 3
A5 = 3 + 2 = 5
A6 = 5 + 3 = 8
A7 = 8 + 5 = 13
A8 = 13 + 8 = 21
A9 = 21 + 13 = 34
A10 = 34 + 21 = 55

Ans: C

-------------------------------------------------------------------------

註解.
此題是模擬程式, 用定義直接遞迴計算, 但在數學上並不是這樣計算,
例如, 在只有計算機, 無電腦的輔助下, 要遞迴計算 A100 非常費時, 數學算法為:
An = An-1 + An-2
An - An-1 - An-2 = 0
此為二階線性齊次遞迴關係式, 其特徵方程式為:
k² - k - 1 = 0
k = ( 1 ± √5 ) / 2 , 所以 :
An = p*[ (1+√5)/2 ]^n + q*[ (1-√5)/2 ]^n

代入初始值 A0 = 0 , A1 = 1 :
0 = A0 = p + q ..... (1式)
1 = A1 = p*[ (1+√5)/2 ] + q*[ (1-√5)/2 ] ..... (2式)
由 (1式) 得: q = - p
由 (2式) 得: 2 = (1+√5)p + (1-√5)q = (1+√5)p + (1-√5)(-p) = 2√5 p
p = 2 / (2√5) = 1/√5
q = - p = - 1/√5 , 因此 :
An = (1/√5) * { [ (1+√5)/2 ]^n - [ (1-√5)/2 ]^n }

利用計算機可得:
A10 = 55
A100 ≒ 3.54225 * 10^20


收錄日期: 2021-05-02 14:11:52
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20161005041751AAdFW92

檢視 Wayback Machine 備份