Вычисление факториала на Assembler
Категория: Assembler
2011-08-28 21:16:30
code: #assembler
; ; file: factorial.asm ; This program demonstrates local variables and recursion ; %include "asm_io.inc" segment .data prompt db "Enter a number: ", 0 ans_msg db "! is ", 0 segment .bss input1 resd 1 input2 resd 1 segment .text factorial: ; ; This procedure expects one unsigned integer (n>0) on the stack. ; It returns n! in eax ; push ebp mov ebp,esp sub esp,4 ;make space for a local variable (at ebp-4) mov eax,[ebp+8] ;put parameter in eax cmp eax,0 je done ;if we were finding 0! mov [ebp-4],eax ;else store eax in our local variable dec eax ;compute n-1 push eax ;put it on the stack call factorial ;and find (n-1)! ;oops! forgetting to remove param from stack. see * mul dword [ebp-4] ;then multiply it by our saved value jmp epilog ;and return it done: mov eax,1 epilog: mov esp,ebp ;restore esp (skip over local variables) ; Note *: saved, because we fix esp no matter what ; DON'T DO THIS. I left it in for educational purposes only pop ebp ret global _asm_main _asm_main: enter 0,0 ; setup routine pusha mov eax, prompt call print_string call read_int call print_int push eax mov eax,ans_msg call print_string call factorial add esp,4 ;remove parameter from stack call print_int call print_nl popa mov eax, 0 ; return back to C leave ret
Поделиться: