GCD程序x86汇编语言

时间:2014-03-07 23:57:15

标签: assembly masm irvine32

INCLUDE Irvine32.inc

.data   
        heading     BYTE    "This is a program for GCD.........", 0
        inputX      BYTE    "Enter an integer X: ", 0
        inputY      BYTE    "Enter an integer Y: ", 0
        ansGCD      BYTE    "The value of GCD is: ", 0
        valX        DWORD   ?
        valY        DWORD   ?       

.code
main PROC       
        mov edx, OFFSET heading         ;print header
        call WriteString
        call Crlf

        mov edx, OFFSET inputX          ;input X
        call WriteString
        call ReadDec
        mov valX, eax
        call Crlf

        mov edx, OFFSET inputY          ;inputY
        call WriteString
        call ReadDec
        mov valY, eax
        call Crlf

        mov eax,DWORD ptr[valX]     ;dividend
        mov ebx,DWORD ptr[valY]     ;divisor
        push valY                       ;pushing values into stack
        push valX
        call CalcGdcI
        call Dumpregs

        exit
main ENDP


CalcGdcI PROC
        xor edx, edx
        mov eax, DWORD ptr[esp+8]       ;dividend
        mov ebx, DWORD ptr[esp+4]       ;divisor
        div ebx                         ;eax/ebx
        cmp edx, 0                      ;remainder in edx
        je L1                           ;yes: quit
        call CalcGdcI                   ;no: call CalcGdcI again
L1:
        mov eax, ebx                    ;move the divisor into eax to print
        mov edx, OFFSET ansGCD
        call WriteString
        call WriteDec                   ;Display GCD WriteInt
        call Crlf
        ret 8                           ;clean up the stack
CalcGdcI ENDP

END main

如果数字不完全可分,我得到错误的答案,如(54,24)但可以正常使用,(10,100)...谢谢

1 个答案:

答案 0 :(得分:0)

我认为你应该写一些类似的东西(我已经多年写过汇编):

CalcGdcI PROC
    xor edx, edx
    mov eax, DWORD ptr[esp+8]       ;dividend
    mov ebx, DWORD ptr[esp+4]       ;divisor
loop:
    div ebx                         ;eax/ebx
    cmp edx, 0                      ;remainder in edx
    je L1                           ;yes: quit
    mov eax, ebx                    ;restart with eax = ebx
    mov ebx, edx                    ;and          ebx = edx
    jmp loop
l1: 
    ...