0

I want to calculate this perimeter expression

(hight * 2) + (width * 2)

example:

Enter hight: 3
Enter width: 2
perimeter is : 10

Enter hight: 1
Enter width: 1
perimeter is : 4

.model small
    cr equ 0Dh
    lf equ 0Ah
.data
    msg1 db cr,lf,'Enter hight: $'
    msg2 db cr,lf,'Enter width: $'
    msg3 db cr,lf,'perimeter is : $'
.stack 100h
.code
main    proc
    mov ax,@data
    mov ds,ax
    lea dx,msg1
    mov ah,9h
    int 21h
    mov ah,1h
    int 21h
    sub al,30h
    mov cl,2
    mul cl
    mov bx,ax
    mov ax,@data
    mov ds,ax
    lea dx,msg2
    mov ah,9h
    int 21h
    mov ah,1h
    int 21h
    sub al,30h
    mov cl,2
    mul cl
    mov cx,ax
    mov ax,@data
    mov ds,ax
    lea dx,msg3
    mov ah,9h
    int 21h
    add cx,bx
    mov ah,2h
    int 21h
    mov ah,4ch
    int 21h
main    endp
end main

My code does not give the correct result. How can I fix my code?

Sep Roland
  • 33,889
  • 7
  • 43
  • 76
wato
  • 25
  • 3
  • 3
    It doesn't seem like you are printing your result properly - see: https://stackoverflow.com/questions/30139706/printing-decimal-number-in-assembly-language. – Halt State Jan 05 '21 at 16:08

1 Answers1

0
add cx,bx
mov ah,2h
int 21h

You have put the result in the CX register but the single character output function 02h expects your character in the DL register.

Quick fix:

mov dl, cl
add dl, '0'
mov ah, 02h
int 21h

Since this outputs a single character, you should not expect it to display the two-digit result from your first example (10)!


The longest perimeter (36) you get from inputting 9 twice.
Next code can output numbers in the range [0,99]:

  mov al, cl      ; [0,36]
  aam             ; -> AH = perimeter / 10    AL=perimeter % 10
  add ax, 3030h
  mov cx, ax
  cmp ch, "0"
  je  SkipLeadingZero
  mov dl, ch      ; tens
  mov ah, 02h
  int 21h
SkipLeadingZero:
  mov dl, cl      ; ones
  mov ah, 02h
  int 21h

Some additional advice

  • You don't need to reload the DS segment register each time you output a message

  • You can re-arrange an expression so as to simplify the calculation

      (hight * 2) + (width * 2) <=> (hight + width) * 2
    
  • Multiplication by 2 should be repaced by a single shift to the left.

      (hight + width) * 2 <=> (hight + width) << 1
    

Assuming hight is in BL and width is in CL:

mov al, bl    ; BL=[0,9]
add al, cl    ; CL=[0,9]
shl al, 1     ; -> AL=[0,36]
aam
...
Sep Roland
  • 33,889
  • 7
  • 43
  • 76