简体   繁体   中英

Recursive Assembly Program

The following code is straight out of the book:

 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

Now, when I go to debug the code it does not work. The value in EAX ends up being 78, when the value of 5! is 120. Do I need to initialize certain registers to 0 or am I missing something bigger? A nudge in the right direction would be much appreciated. Thank you!

Nevermind, I figured it out (and feel sheepishly stupid). The value is being returned in hexadecimal format and not decimal format. 78 in hexadecimal converts to 120 in decimal, so the program works just fine. Sorry for the (unnecessary) post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM