问题
I am trying to make a program that first takes n inputs from the user, and then calculates the sum of those numbers. Then I want the program to print if the sum is an even or an odd number.
For example if the user types in 3, he/she will have to type in 3 numbers (for example 3, 2, 5): then the program will calculate the sum of those (3 + 2 + 5) and print out if the answer (10) is an odd or an even number.
I thought I coded it right, but it doesn't run in the LMC simulator, can someone please help me finding the error?
My code:
INP
STA b
ab INP
STA a
LDA total
ADD a
STA total
STA count
LDA b
SUB one
STA b
BRZ number
BRP loop
bc LDA count
SUB two
STA count
BRZ evennumber
BRP number
LDA total
OUT
LDA space
OTC
OTC
LDA o
OTC
LDA d
OTC
OTC
LDA e
OTC
HLT
cd LDA total
OUT
LDA space
OTC
OTC
LDA p
OTC
LDA A
OTC
LDA r
OTC
HLT
a DAT 0
b DAT 0
total DAT 0
one DAT 1
two DAT 2
count DAT 0
o DAT 111
space DAT 32
d DAT 100
e DAT 101
p DAT 112
A DAT 97
r DAT 114
回答1:
The main problem in your code is that the labels mismatch.
On the one hand you have defined the following labels:
- ab
- bc
- cd
...but you have referenced the following labels:
- loop
- number
- evennumber
As a consequence your code is not valid ... it will not parse.
The second set of labels make more sense, while "ab", "bc", "cd" are meaningless: they don't help the viewer of your code to understand what they are about. So align your code with the second set.
Also, it is not defined whether LMC is case sensitive, so using a variable name a
and another A
is not certain to be supported. Instead, give meaningful names. The first a
is in fact the number you input and need to add to the sum, so maybe call it summand
instead of a
. The other A
could then be called a
, as it really represents the letter "a". b
is also meaningless. It represents the number of inputs that are expected, so maybe call it inputs
.
Taking that together, your code would look like this:
#input: 2 4 5
INP
STA inputs
loop INP
STA summand
LDA total
ADD summand
STA total
STA count
LDA inputs
SUB one
STA inputs
BRZ number
BRP loop
number LDA count
SUB two
STA count
BRZ evennumber
BRP number
LDA total
OUT
LDA space
OTC
OTC
LDA o
OTC
LDA d
OTC
OTC
LDA e
OTC
HLT
evennumber LDA total
OUT
LDA space
OTC
OTC
LDA p
OTC
LDA a
OTC
LDA r
OTC
HLT
summand DAT 0
inputs DAT 0
total DAT 0
one DAT 1
two DAT 2
count DAT 0
o DAT 111
space DAT 32
d DAT 100
e DAT 101
p DAT 112
a DAT 97
r DAT 114
<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.72/lmc.js"></script>
来源:https://stackoverflow.com/questions/64386777/program-to-sum-input-numbers-is-not-working