Issue
This Content is from Stack Overflow. Question asked by Edrawrxd
INP
STA A
INP
STA B
LDA 99
STA C
loop LDA A
SUB B
STA A
LDA C
ADD Y
STA C
LDA A
BRP loop
LDA C
OUT
HLT
A DAT
B DAT
C DAT
Y DAT 1
Hello I am new to Little Man computer, this number division program should return 6 when A is input as 24 and B as 4, but when I run it, it outputs 7 which makes no sense. I know it loads A into the accumulator at the start and end of the while loop so I didn’t include that in the trace table. I’m not a credible user yet it makes me use links for pictures
Solution
Here are some issues:
BRP
will also branch when the accumulator has zero, which explains why you get 7 instead of 6 for your test case.Loading zero into the accumulator should better be done from a labeled mailbox, not from hardcoded 99. As
HLT
is zero, you could give that line the labelzero
and useLDA zero
instead ofLDA 99
Instead of A, B, C and Y use some more descriptive names, like
numerator
,divisor
,quotient
andone
.The way
BRP
works may differ a bit on different LMC emulators. To make sure you have the greatest compatibility, performBRP
immediately afterSUB
, because the value left in the accumulator after aSUB
-overflow can be different on different emulators, and secondly, some emulators may reset the negative-flag when executingLDA
, makingBRP
to always branch afterLDA
. By placing theBRP
right afterSUB
you also solve the first problem.
Here is a runnable corrected version. It loads with your example input, but the little GUI allows you to test with other inputs:
#input: 24 4
INP
STA numerator
INP
STA divisor
LDA zero
loop STA quotient
LDA numerator
SUB divisor
BRP continue
LDA quotient
OUT
zero HLT
continue STA numerator
LDA quotient
ADD one
BRA loop
numerator DAT
divisor DAT
quotient DAT
one DAT 1
<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.816/lmc.js"></script>
This Question was asked in StackOverflow by Edrawrxd and Answered by trincot It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.