-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