找到你要的答案

Q:Factorial of a number in assembly

Q:汇编中阶乘的阶乘

I am trying to find Factorial of a number but a unexpected output is coming. for 5 it should be 120 but 00 is coming. please Help in the following code Sometimes it goes into infinite loop.

.model small
.stack 100h
.data
buffer db 10 dup('$')
n dw 5  
.code
main proc 

    mov ax , @data
    mov ds ,ax
    mov ax , n
    mov bx , offset buffer
    mov cx , 1 

 l1 : 

inc cx  
mul cx
cmp cx , n
jne l1

l2 : 
mov dx, 0 
mov cx ,10  
div cx 
add dl,48 
mov [bx], dl 
inc bx
cmp ax, 0 
jne l1      

mov dx , offset buffer ; moving address to dx
mov ah,9 ; printing string
int 21h

mov ax, 4c00h
int 21h


main endp
end main    

我试图找出一个数字的阶乘,但一个意想不到的输出来。5应该是120,但00是未来。请帮助下面的代码,有时它进入无限循环。

.model small
.stack 100h
.data
buffer db 10 dup('$')
n dw 5  
.code
main proc 

    mov ax , @data
    mov ds ,ax
    mov ax , n
    mov bx , offset buffer
    mov cx , 1 

 l1 : 

inc cx  
mul cx
cmp cx , n
jne l1

l2 : 
mov dx, 0 
mov cx ,10  
div cx 
add dl,48 
mov [bx], dl 
inc bx
cmp ax, 0 
jne l1      

mov dx , offset buffer ; moving address to dx
mov ah,9 ; printing string
int 21h

mov ax, 4c00h
int 21h


main endp
end main    
answer1: 回答1:

The jump at the end of your l2 loop is incorrect. You're jumping to l1 when you should be jumping to l2.

Also, in your l1 loop you inc and mul before you decide whether to exit the loop. So in the case where n is 5 you'll get 5 * 2 * 3 * 4 * 5 (which is 600).

在L2循环结束时的跳转不正确。你跳的时候你应该跳到L1 L2。

另外,在L1回路你公司多在你决定是否退出循环。因此,在n是5的情况下,你会得到5 * 2 * 3 * 5 *(这是600)。

assembly