谁可以用汇编写递归程序,如f(n)=n*f(n

2025-06-22 22:23:38
推荐回答(1个)
回答1:

.model small
.386
;---------------------------------------------------------------
.code
start:
      push  cs
      pop   ds
      
      mov   ah,09h
      mov   dx,offset msg1
      int   21h

      mov   dx,offset InputBuffer
      sub   bx,bx
      mov   ah,3fh
      mov   cx,80h
      int   21h
      
      mov   si,offset InputBuffer
      sub   ebx,ebx
      sub   eax,eax
      
@Skip:     ;Skip blank and table
      mov   al,[si]
      inc   si
      cmp   al,' '
      je    @Skip
      cmp   al,09h
      je    @Skip
      
@ReadBegin:
      sub   al,'0'
      jl    @ReadEnd
      cmp   al,9
      jg    @ReadEnd
      imul  ebx,ebx,0ah
      add   ebx,eax
      mov   al,[si]
      inc   si
      jmp   @ReadBegin
@ReadEnd:

      mov   eax,ebx
      shr   eax,10h  ;ax放的是ebx的高位值
      push  ax
      push  bx
      call  Fact
      
      push  ax
      shr   eax,10h
      push  ax

      mov   eax,ebx
      call  PutNumber
      
      mov   ah,09h
      mov   dx,offset msg2
      int   21h
      
      pop   ax
      shl   eax,10h
      pop   ax
      call  PutNumber
      
      mov   ah,4ch
      int   21h
;---------------------------------------------------------------
Fact  proc  near   ;求阶乘的递归函数,参数在栈里,结果值在eax
      push  bp
      mov   bp,sp
      ;
      mov   eax,dword ptr [bp+04h]
      mov   edx,eax
      dec   edx
      jz    @FactEnd
      mov   ecx,edx  ;cx为n-1的高16位,dx为n-1的低16位
      shr   ecx,10h
      push  cx
      push  dx
      call  Fact
      mov   edx,dword ptr [bp+04h]
      mul   edx
@FactEnd:
      ;
      pop   bp
      ret   4
Fact  endp
;---------------------------------------------------------------
PutNumber   proc  near
            push  bp
            mov   bp,sp
            ;
            mov   ecx,0ah
@PushNumber:
            sub   edx,edx
            div   ecx
            push  dx
            or    eax,eax
            jne   @PushNumber
@PopNumber:
            pop   dx
            add   dl,'0'
            mov   ah,02h
            int   21h
            cmp   bp,sp
            jnz   @PopNumber
            ;
            pop   bp
            ret
PutNumber   endp
;---------------------------------------------------------------
msg1              db    '求n的阶乘,请输入n的值:$'
msg2              db    '!=$'
InputBuffer       db    80h dup(?)
;---------------------------------------------------------------
end   start