【问题标题】:Assembly Language calculating recursive function汇编语言计算递归函数
【发布时间】:2017-07-04 18:48:59
【问题描述】:

我正在尝试在程序集上实现以下函数作为递归函数调用。

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
  • 我该如何解决?我的逻辑是否正确执行?
  • ebp 不是ebx,也没有弹出任何结果。不,你的逻辑是错误的。如果您查看您的伪代码,您会发现您需要调用f() 两次。将第一次调用的返回值存储在局部变量中(您需要从堆栈中分配),然后使用该局部变量和第二次调用的返回值执行计算。
  • 是什么导致了您的问题?完全一样,只是n-2
  • 我添加以下内容 ** - dec eax - add ebx, eax - mov eax,ebx ** 但是这一次,而不是函数 eax 值 f(n-2) 仅 (n-2)值被添加到计算中。我的问题是,我应该在返回事实下再调用一次递归吗?或者我需要得到 f(n-2) 值的地方

标签: recursion assembly x86 procedure


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多