问题
Hi I'm trying to write a lc3 assembly program which computes the square of a number and stores it in r0, the integer is given as a parameter and is located in r1, the problem i noticed while debugging is during the first pass it initially adds 2, but the second pass it fails to add another 2 to r0 - My code is below any help is appreciated
.orig x3FF8
ld r1,n
ld r5,n
square
add r2,r1,#0
add r5,r5,#-1
add r0,r2,#0
brzp square
brn theend
theend
halt
n .fill #2
.end
my final code thanks to the user who helped:
.orig x3FF8
ld r1,n
ld r5,n
square
add r2, r2,r1
add r5,r5,#-1
brp square
theend
halt
n .fill #4
.end
回答1:
If I remember LC-3 syntax correctly, add r2,r1,#0
does r2 = r1 + 0
, so it was never actually adding to r2
, just overwriting it with r1
.
You want something like that outside the loop to initialize r2
.
But inside the loop, you want add r2, r2, r1
which does r2 = r2 + r1
, i.e. r2 += r1
.
I don't understand why you have add r0,r2,#0
inside the loop as well.
If you want the final result in r0
, accumulate it in r0
in the first place. Of if that was supposed to be a sum of sums, then you have the same bug.
Also note that add r5,r5,#-1
needs to be last so condition code flags are set from it for the loop branch, not from add r0, r0, r2
or whatever else you need inside the loop.
Also: brn theend
is totally useless: theend
is on the next line, and execution continues to the next line on its own. You don't have to jump over whitespace in the source!
来源:https://stackoverflow.com/questions/47765417/lc3-assembly-square-of-n