简体   繁体   中英

Assembly Language: How to compare an input number in 8086?

The problem is to ask a user to input any number. And compare the entered number with a pre-defined constant number. Then output a message that number the entered is either greater or less than or equal to the defined number. In this example my predefined number is 27.

My code is:

   .MODEL small
   .STACK 100h
   .DATA
promptmsg DB 'Please enter a number [1..100]',13,10,'$'
greatermsg db 'You have entered a greater number', 13, 10, '$'
lessmsg db 'You have entered a lesser number', 13 , 10, '$'
correctmsg db 'You have hit the right number', 13, 10, '$'
numbr dw 27
   .CODE
   .startup
   mov  ax,@data
   mov  ds,ax                   
   lea dx, promptmsg
   mov  ah,9    
   int  21h                     
   mov ah, 0ah
   int 21h
   mov ah, 9
   int 21h
   mov bx, numbr
   cmp ax, bx
   jb lesser
   ja greater
correct:
   mov dx, offset correctmsg
   mov ah, 09h
   int 21h
   jmp endexe
greater:
   mov dx, offset greatermsg
   mov ah, 09h
   int 21h
   jmp endexe
lesser:
   mov dx, offset lessmsg
   mov ah, 09h
   int 21h
endexe:
   mov  ah,4ch                 ;DOS terminate program function
   int  21h                    ;terminate the program
   END

If I input any number regardless it is greater or less than or equal to the predefined number, it always jumps to greater. Is there any problem with my code, that failed to recognize my input number?

Update: Corrected the variable numbr instead of ans.

I see this line in your code:

mov bx, ans

However, I don't see 'ans' defined anywhere. Did you mean 'numbr'?

I see a few other problems. Your code seems to think that the result of int 21h/ah=0ah operation will return a number via the ax register. It won't. According to the first reference I found while googling, the operation returns a string in the buffer referenced by ds:dx. Which, BTW, your code does not explicitly establish-- when int 21h/ah=0ah, is called, ds:dx still points to promptmsg, so the operation will overwite the prompt.

So it looks like the code prints the prompt, asks for input, and then prints the input back to the user. By the time it gets to the comparison:

cmp ax, bx

You have already put 9 into the upper half of ax, so it makes sense that the 'greater' path is always taken. But again, that doesn't matter, since the read instruction doesn't return input data via ax, but rather in the buffer pointed to by ds:dx.

However, even if you did load the first byte referenced by ds:dx, your code still would not work as you expect. You will need to convert a sequence of ASCII characters into a number. Ie, '9' -> 9, '100' -> 100. That will require a little more code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM