简体   繁体   English

递归汇编程序

[英]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! EAX中的值最终为78,而值为5! is 120. Do I need to initialize certain registers to 0 or am I missing something bigger? 是120。我需要将某些寄存器初始化为0还是缺少更大的寄存器? 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. 十六进制的78转换为十进制的120,因此程序运行正常。 Sorry for the (unnecessary) post. 对不起(不必要的)帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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