.386
.model flat,stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD
INCLUDE Irvine32.inc
.data
prompt BYTE "Please enter the lower bound: ", 0
prompt2 BYTE "Please enter the upper bound: ", 0
lowerbound SDWORD ?
count DWORD ?
.code
main PROC
mov ecx, 3
L1:
mov count, ecx
mov ecx, 30
mov edx, OFFSET prompt
call WriteString
call ReadInt
mov lowerbound, eax
mov edx, OFFSET prompt2
call WriteString
call ReadInt
mov ebx, lowerbound
L2:
call BetterRandomRange
call WriteInt
call crlf
loop L2
mov ecx, count
loop L1
exit
INVOKE ExitProcess,0
main ENDP
BetterRandomRange PROC ;loop 3 times
sub eax, ebx
call RandomRange
add eax, ebx this keeps in within range but causes a division by zero error
;sub eax, ebx no error but slightly out of range for the 30 iterations
ret
BetterRandomRange ENDP
END main
I'm trying to complete the problem of generating an integer between M and N-1 based on user input, where M is in EBX (lower bound) and N is in EAX (upper bound) and the number is returned in EAX.
I've somewhat located the error because the upper bound is not stored in EAX before calling BetterRandomRange. However, I'm unsure on how to fix this because EAX and EBX have the correct bound values in the first iteration. I'm new to assembly and still learning it so it's a bit confusing for me. Any help would be appreciated!
When you call
BetterRandomRangethe first time, it will change the value ineax. In additionWriteIntandcrlfwill likely change it too aseaxis not preserved across functions. So in the second iteration,eaxcontains whatevercrlfleft there rather than the upperbound.What you need to do is to store the upperbound (perhaps a static var as you do with
lowerbound) and reload it before calling `BetterRandomRange each time in the loop.