我试图在程序集上实现下面的函数作为递归函数调用。
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
答案 0 :(得分:0)
INCLUDE Irvine32.inc
.CODE
main PROC
mov ecx, 7
push ecx
call RECURSIVE
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,[ebp+8] ; no, return 1
jmp L2 ;return to the caller
L1: dec eax
push eax
call RECURSIVE
ReturnFact: shl eax,1
push eax
mov eax, [ebp+8]
sub eax, 2
push eax
call RECURSIVE
add eax, [ebp-4]
L2: mov esp, ebp
pop ebp ;return eax
ret 4 ;clear stack
RECURSIVE ENDP
END main