2013-06-13 49 views
0

我想在x86程序集中迭代地找到GCD。不知何故,循環在第一次迭代之後保持終止,因爲餘數= 0。任何想法爲什麼?GCD迭代地在x86 intel程序集中

;while r > 0 do 
; Set b = a 
; Set a = r 
; Set r = b % a 
;Output a 


calculation_loop: 
    cmp  remainder, 0     ;check if remainder is 0 
    je  end_of_calc      ;if it is, value in intA is GCD 

    mov  ecx, intA      ;set b = a 
    mov  intB, ecx 

    mov  ecx, remainder     ;set a = r 
    mov  intA, ecx 

    mov  edx, 0       ;clearing remainder 

    mov  ecx, intA      ;process remainder and store in variable 
    div  ecx 
    mov  remainder, edx 


    mov  eax, remainder 
    call WriteInt 
    call Crlf 

    jmp  calculation_loop 

end_of_calc: 

    call Crlf 
    mov  eax, intA 
    mov  edx, OFFSET outputPrompt 
    call WriteString 
    call WriteInt 
    call Crlf 

回答

0

我敢打賭,你達到calculation_loop的第一次迭代之前remainder設置爲0,這就是爲什麼它會立即跳出calculation_loop。這是你的問題,但是解決方案呢?

您應該以不同的方式訂購您的代碼,因此它的功能類似於do-while而不是while循環。我重新排列你的指令,從而使代碼的功能類似於一個do-while循環:

; calculation loop 
calculation_loop: 
    ; set b to a 
    mov ecx, intA 
    mov intB, ecx 
    ; set a to r 
    mov ecx, remainder 
    mov intA, ecx 
    ; clear remainder (I don't think this is nessesary, can't say for sure) 
    mov edx, 0 
    ;process remainder and store in variable 
    mov ecx, intA      
    div ecx 
    mov remainder, edx 
    ; write data 
    mov eax, remainder 
    call WriteInt 
    call Crlf 
    ; if the remainder != 0, go again 
    cmp remainder, 0 
    jne calculation_loop 

通知我該怎麼辦,其餘檢查在循環的最後一跳,後剩餘的已被計算。希望這可以解決你的問題。

注意:我不記得在x86中如何完成整數除法,所以我不能說其他代碼是否有可能是錯誤的。但我認爲我解決了有條件跳轉的問題。

最後,還有一個小費。如果你正在編寫這種數字處理代碼,尋找錯誤的好方法是一次一步地通過你的代碼指令,看看寄存器如何改變(通過調試器)。如果你還沒有這樣做,我強烈建議。