求和输入数字的程序不起作用



我正在尝试制作一个程序,该程序首先接受用户的n输入,然后计算这些数字的总和。然后,如果和是偶数或奇数,我想让程序打印出来。

例如,如果用户键入3,他/她将不得不键入3个数字(例如3、2、5(:然后程序将计算这些数字的总和(3+2+5(,并打印出答案(10(是奇数还是偶数。

我以为我编码对了,但它没有在LMC模拟器中运行,有人能帮我找到错误吗?

我的代码:

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

代码中的主要问题是标签不匹配。

一方面,定义了以下标签:

  • ab
  • bc
  • cd

。。。但是引用了以下标签:

  • 循环
  • 数字
  • 偶数

因此,您的代码无效。。。它将不会解析。

第二组标签更有意义;ab"bc"cd";毫无意义:它们不能帮助代码的查看器理解它们的内容。因此,将您的代码与第二组代码对齐。

此外,还没有定义LMC是否区分大小写,因此不一定支持使用变量名a和另一个A。相反,给出有意义的名字。第一个a实际上是您输入的数字,需要添加到和中,所以可以将其称为summand而不是a。另一个A可以被称为a;a";。CCD_ 8也是没有意义的。它表示预期的输入数量,所以可以称之为inputs

综合起来,你的代码会是这样的:

#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>

相关内容

最新更新