2013-09-24 83 views
1

所以我開始在Windows機器上使用NASM學習16位程序集。 如果我已經創建了這個小程序,要求用戶輸入,然後確定輸入是否在一定範圍內(0到9)。如果是這樣,它會繼續查看該值是否可以被三整除,如果不是,則它應該循環並要求用戶提供另一個值。這是我的代碼:16位彙編程序

org 0x100 
    bits 16 
;jump over data declarations 
    jmp main 

input: 
    db 6 
    db 0 
user: times 6 db ' ' 

cr_lf: db 0dh, 0ah, '$' 

message: db 'Please enter the number you select between 0 and 9:','$' 
errormsg: db '***', 0ah, 0dh, '$' 
finalMsg: db 'Number is divisible by 3!', 0ah, 0dh, '$' 
finalErrorMsg: db 'Number is not divisible by 3!', 0ah, 0dh, '$' 

outputbuffer: db '  ', '$' 

;clear screen and change colours 
clear_screen: 
    mov ax, 0600h 
    mov bh, 17h ;white on blue 
    mov cx, 00 
    mov dx, 184Fh 
    int 10h 
    nop 
    ret 

move_cursor: 
    mov ah, 02 
    mov bh, 00 
    mov dx, 0a00h 
    int 10h 
    ret 

;get user input 
get_chars: 
    mov ah, 01 
    int 21h 
    ret 

;display string 
display_string: 
    mov ah, 09 
    int 21h 
    ret 

errstar: 
    mov dx, errormsg  
    call display_string 
    int 21h 
    jmp loop1 

nextphase: 
    cmp al, 30h  ;compare input with '0' i.e. 30h 
    jl errstar  ;if input is less than 0, display error message 
    ;else 
    call ThirdPhase  ;input is clearly within range 

ThirdPhase: 
    xor dx, dx  ;set dx to 0 for the divide operation 
    ;at this point al has the value inputted by the user 
    mov bl, 3 ;give bl the value 
    div bl  ;divide al by bl, remainder stored in dx, whole stored in ax 
    cmp dx, 0 ;compare remainder to 0 
    jg notEqual ;jump to not divisible by three as remainder is greater than 0 
    je end 

notEqual: 
    mov dx, finalErrorMsg 
    call display_string 
    int 20h 

end: 
    mov dx, finalMsg 
    call display_string 
    int 20h 

;main section 
main: 
    call clear_screen ;clear the screen 
    call move_cursor ;set cursor 

loop1: 
    mov dx, message  ;mov display prompt into dx 
    call display_string ;display message 
    call get_chars  ;read in character 
    ;at this point a character value is inputted by the user 
    cmp al, 39h  ;compare with '9' i.e. 39h 
    jle nextphase  ;if value is less than or equal to 9, move onto next phase 
    jg errstar  ;else call error and loop 

無論如何,所以值範圍檢查工作正常,循環工作也很好。我得到的問題是在三個第三階段中可以分割的問題。 我的理解是,首先我需要確保dx包含值0.然後將值3移動到bl。現在,al包含用戶輸入,bl包含值3,並且dx爲0. 然後在div bl部分中,al除以bl,其爲3的值。餘數存儲在dx中,並且如果與0進行比較並且發現更大,那麼它應該跳轉到notEqual部分,否則跳到結束部分。

因爲它是現在,我總是得到finalMsg顯示,這種情況應該只是要顯示如果值是3。

任何完全除盡有一些建議。 謝謝。 JP。

+0

打印'finalErrorMsg'後不會終止程序。所以,之後它還會打印'finalMsg'。快速修復:在到達'end'標籤之前跳轉到'loop1'。 – Kamiccolo

回答

3

你正在做一個div bl,除以一個字節。因此,商數在al中,餘數在ah中,而不是在axdx中,正如代碼所假定的那樣。請確保您在div之前清除ah,因爲您的分紅是al中的單個字節。

+0

好的,所以我已經把比較語句改爲:cmp啊,0但是,現在它總是跳轉到不能被三部分整除。這與之前的情況相反。 –

+1

@Slasher_X你是否事先清楚'ah'? – lurker

+0

啊哈!清算啊事前創造了奇蹟。 –