◎ 執行下列程式片段後,K值為何?(A) 1 (B) 5 (C) 15 (D) 120 [商業語文]
Rem MAIN PROGRAM K = GAME(5) Print K End Function GAME(X) If (X > 1) Then GAME = X * GAME(X - 1) Else GAME = 1 End If End Function
【答案】 (D)
【解析】
GAME(5) = 5 * GAME(4)
GAME(4) = 4 * GAME(3)
GAME(3) = 3 * GAME(2)
GAME(2) = 2 * GAME(1)
接著開始代入:
GAME(1) = 1
GAME(2) = 2 * GAME(1) = 2 * 1
GAME(3) = 3 * GAME(2) = 3 * (2 * 1)
GAME(4) = 4 * GAME(3) = 4 * (3 * 2 * 1)
GAME(5) = 5 * GAME(4) = 5 * (4 * 3 * 2 * 1) = 120。
◎ 在Visual Basic的程式中,定義了一個遞迴函數X如下所示,則 Print X(5)的結果為何?
(A) 12 (B) 15 (C) 16 (D) 產生錯誤訊息
Function X(N) If N=0 Then X = 0 Else X = X(N-1) + N End If End Function
【答案】 (B)
【解析】
X(5) = X(4) + 5
X(4) = X(3) + 4
X(3) = X(2) + 3
X(2) = X(1) + 2
X(1) = X(0) + 1
X(0) = 0
接著開始代入:
X(0) = 0
X(1) = 0 + 1 = 1
X(2) = X(1) + 2 = 1 + 2 = 3
X(3) = X(2) + 3 = 3 + 3 = 6
X(4) = X(3) + 4 = 6 + 4 = 10
X(5) = X(4) + 5 = 10 + 5 = 15