-1
我想在彙編上實現下面的函數作爲遞歸函數調用。彙編語言計算遞歸函數
Int f(n)
if (n<=3) return n;
else return 2 * f(n-1) + f(n-2);
當我運行代碼時,我收到1作爲結果。 請指點
INCLUDE Irvine32.inc
.CODE
main PROC
push 5
call RECURSIVE ; calculate the below function
call WriteDec
call Crlf
exit
main ENDP
;------------------------------
RECURSIVE PROC
; Calculates int f(n)
; if (n<=3) returns n
; else return 2*f(n-1)+f(n-2)
;------------------------------
push ebp
mov ebp,esp
mov eax,[ebp+8] ;get n
cmp eax,3 ;n > 3 ?
ja L1 ; yes, continue
mov eax,1 ; no, return 1
jmp L2 ;return to the caller
L1: dec eax
push eax
call RECURSIVE
ReturnFact:mov ebx,[ebp+8] ;get n-1
shl ebx,1 ;multiply by 2
add ebx,[ebp+16] ;add n-2 and save
L2: pop ebp ;return eax
ret 4 ;clear stack
RECURSIVE ENDP
END main
'[EBP + 16]'是不好的做法,即使它可能工作。您正試圖訪問調用者的本地變量。您正在使用'ebx'進行計算,但是放棄了結果,因此您只能返回'mov eax,1'。 – Jester
我該如何解決它?我的邏輯是否正確執行? – mwater07
'ebp'不是'ebx',也不會彈出任何結果。不,你的邏輯錯了。如果你看看你的僞代碼,你可以看到你需要調用'f()'**兩次**。將第一次調用的返回值存儲在局部變量中(您將需要從堆棧中分配),然後使用該局部變量和第二次調用的返回值執行計算。 – Jester