递归装配程序

时间:2014-11-04 15:44:20

标签: assembly recursion x86 masm irvine32

以下代码直接出书:

 INCLUDELIB C:\Irvine\Kernel32.lib
 INCLUDELIB C:\Irvine\Irvine32.lib
 INCLUDE C:\Irvine\Irvine32.inc

 .code
 main PROC
     push 5             ; calc 5!
     call Factorial     ; calculate factorial (EAX)
     call WriteDec      ; display it
     call Crlf
     exit
 main ENDP

 ;----------------------------------------------------------
 Factorial PROC
 ; Calculates a factorial.
 ; Receives: [ebp+8] = n, the number to calculate
 ; Returns: eax = the factorial of n
 ;----------------------------------------------------------
 push ebp
mov ebp,esp
mov eax,[ebp+8]     ; get n
cmp eax,0                 ; n > 0?
ja L1                ; yes: continue
mov eax,1                 ; no: return 1 as the value of 0!
jmp L2               ; and return to the caller

L1: dec  eax             ; Factorial(n-1)
push eax
call Factorial

; Instructions from this point on execute when each
; recursive call returns.

ReturnFact:
mov ebx,[ebp+8]     ; get n
mul ebx              ; EDX:EAX = EAX * EBX

L2: pop ebp         ; return EAX
ret 4                ; clean up stack
Factorial ENDP
END main

现在,当我去调试代码时,它不起作用。当值为5时,EAX中的值最终为78!是120.我需要将某些寄存器初始化为0还是我错过了更大的东西?向正确的方向轻推将非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

没关系,我把它搞清楚了(并感到羞怯)。该值以十六进制格式返回,而不是十进制格式。十六进制的78转换为十进制的120,所以程序工作得很好。抱歉(不必要的)帖子。