Assembly Divide by zero
Asked Answered
H

1

0

I am trying to write code for a program to calculate the average of an array but I get the divide by zero error, I googled the error and it seems that it is a divide overflow but I didn't understand what should I do in my program to work. Here is my code:

`DATA SEGMENT
msg1 db 0dh,0ah,"Please enter the length of the array: $"
msg2 db 0ah,0ah,"Enter number: $"
msg3 db 0dh,0ah,"Array average is: $"
val db ?

DATA ENDS

CODE SEGMENT
ASSUME CS:CODE, DS:DATA

START:
mov ax,data
mov ds,ax

mov dx,offset msg1
mov ah,09h
int 21h

mov ah,01h
int 21h
sub al,30h

mov bl,al
mov cl,al
MOV AL,00
MOV VAL,AL
lbl1:
mov dx,offset msg2
mov ah,09h
int 21h

mov ah,01h
int 21h
sub al,30h

add al, val
mov val,al
loop lbl1

lbl2:
mov dx,offset msg3
mov ah,09h
int 21h

mov al, val

div bl
add ax,3030h
mov dx,ax
mov ah,02h
int 21h

mov ah,4ch
int 21h

Code ends
end Start
CODE ENDS`
Hedgepeth answered 5/8, 2016 at 11:57 Comment(0)
L
1

div bl divides ax by bl and stores the quotient in al, and the remainder in ah. The quotient must be in the range 0x00..0xFF, or you'll get a division overflow.

The last thing you set ah to before the division is 9. Since ah is the most significant part of ax that means ax will have the value 0x9XY (where XY are any hexadecimal digits) when you do the division. So to get a quotient that's <=0xFF you would have to divide by at least 10.

The solution is to clear ah before the division (xor ah,ah or mov ah,0).

Lesslie answered 5/8, 2016 at 12:39 Comment(5)
I tried but still no success. Like this? mov al, val xor ah,ah div bxHedgepeth
@Hedgepeth Now you're doing div bx instead of div bl. Are you sure that's what you want?Copyread
In your question you use div bl, not div bx. The answer depends on the exact variant of div that is used.Lesslie
Yeah, it works now, thank you for the answer and the explanation, I understood now.Hedgepeth
@user3848412: See also the canonical answer about zeroing the [e/r]dx before div, linked from the x86 tag wiki's FAQ sectionCanoewood

© 2022 - 2024 — McMap. All rights reserved.