(ASSEMLBY MASM)中的阶乘数大于12

时间:2015-10-11 11:14:08

标签: assembly masm

我想在masm中创建一个程序来查找1到20之间的任何数字的阶乘,但是我的程序对于1到12之间但不是更大的数字工作正常,而我的妈妈因为你&#39告诉我39;重新使用eax寄存器,这些寄存器不能保存大于32位的整数值,因此它将存储您的高位将在edx中,而在eax中则更低。 这是我的代码:

.model small
.stack 100h
.386
.data
.code

main proc

mov eax, 13               ;user input, for 12 fac= 479001600, for 13 incorrect
mov ecx,eax
sub eax,eax
mov eax,1

loop1:
mul ecx
loop loop1

call outdec; it will print whatever in eax

main endp

;--------------------------------------------------------------

outdec proc   ;  Start of my outdec proc working accurately.
push eax
push ebx
push ecx
push edx

cmp eax,0
jge end_if

push eax
mov ah,2
mov dl,'-'
int 21h
pop ax
neg ax
end_if:

mov ebx,10
mov cx,0
rep_loop:
mov dx,0
div ebx
push edx
inc cx
cmp eax,0
jne rep_loop

mov ah,2
prent_loop:
pop edx
add dl,30h
int 21h
loop prent_loop

pop edx
pop ecx
pop ebx
pop eax
ret 
outdec endp

end main
;---------------------------------------------------------------

根据我的建议,我相应地修改了我的代码,但仍然无法得到任何东西     以下是我修改过的代码,outdec proc没有发生任何变化。

main proc

mov eax, 13               ;user input, for 12 fac= 479001600, for 13 incorrect
mov ecx,eax
sub eax,eax
mov eax,1

loop1:
mul ecx
loop loop1

push edx    ; storing numbers of edx in stack
call outdec ; it will print whatever in eax
pop eax     ; supplanting values from stack to eax

call outdec ; again calling outdec
main endp

但它除了最后打印0外什么也没做。

1 个答案:

答案 0 :(得分:3)

您的循环每次迭代都没有跟踪mul结果的高dword。因为你正在向后乘以"倒退" (从13开始,一直到1),当您到达n==2时,您将获得超过32位的产品。此时eax变为1932053504而edx变为1.但是你不能在任何地方保存1,然后你执行循环的最后一次迭代,你将计算1932053504 * 1,它将为您提供eax == 1932053504edx == 0

另一个问题是您将64位结果打印为两个独立的32位数字。如果你在底座2或底座16上打印它们会很好(虽然在这种情况下你应该先打印edx)但是对于底座10你不会得到正确的输出。打印时,需要将结果视为单个64位值。

以下是一个工作实现的示例,以及一些解释这些变化的评论:

mov ecx, 13       ; n
mov eax,1
xor esi,esi       ; will be used to hold the high dword of the 64-bit product

loop1:
mul ecx           ; multiply the low dword by ecx
xchg esi,eax      ; swap eax and esi temporarily
mov ebx,edx       ; save the high dword of eax*ecx
mul ecx           ; multiply the high dword by ecx
add eax,ebx       ; and add the carry from the low-order multiplication
xchg esi,eax      ; swap eax and esi back
loop loop1

call outdec64     ; it will print whatever is in esi:eax

mov ax,0x4c00
int 0x21


;--------------------------------------------------------------

outdec64:
push eax
push ebx
push ecx
push edx

mov ebx,10
mov cx,0
rep_loop:
xor edx,edx    ; clear edx prior to the high-order division
xchg esi,eax
div ebx        ; divide the high dword of our input by 10, the remainder will carry over to the low-order division
xchg esi,eax
div ebx        ; divide the low dword of our input by 10
push edx       ; and save the remainder for printing
inc cx
cmp eax,0
jne rep_loop

mov ah,2
prent_loop:
pop edx
add dl,30h
int 21h
loop prent_loop

pop edx
pop ecx
pop ebx
pop eax
ret 
相关问题