我的程序需要接受3个输入,然后检查它们是否形成Pythagorean三元组。我使用小人电脑来做到这一点,因此我使用LMC组装。如果你想要了解更多关于可以使用的命令的信息,或者下载我正在使用的模拟器,下面是我迄今为止编写的代码。LMC - 有效检查Little Man Computer Assembly中的^ 2 + b^2 = c^2
#Valid mnemonics are:
# HLT, ADD, SUB, STO, LDA,
# BR, BRZ, BRP, IN, OUT, DAT
# The first part of the program will sort a,b and c, so that they will always be in order from
# a,b,c
IN #get first input
STO c
IN #get second input
STO b
IN #get third input
STO a
SUB b #Test if a>b
BRP swapAB
BR next1
swapAB LDA b #Swaps a and b
STO temp
LDA a
STO b
LDA temp
STO a #continues on to next1
next1 LDA b #Test if b>c
SUB c
BRP swapBC
BR end #All sorted
swapBC LDA c #Swaps b an c
STO temp
LDA b
STO c
LDA temp
STO b
BR next2
next2 LDA a #tests new a>b
SUB b
BRP swapAB
end LDA a #begin the process of squaring a
STO total
SUB one
STO count
loop1 LDA total
ADD a
STO total
LDA count
SUB one
STO count
BRZ endsq1
BR loop1
endsq1 LDA total
STO d #stores a*a in d
OUT #for testing. Outputs a*a
SUB total
STO total
LDA b #Begins squaring b
STO total
SUB one
STO count
loop2 LDA total
ADD b
STO total
LDA count
SUB one
STO count
BRZ endsq2
BR loop2 #end of squaring b
endsq2 LDA total
STO e #stores b*b in e
OUT
SUB total
STO total
LDA c #begin squaring c
STO total
SUB one
STO count
loop3 LDA total
ADD c
STO total
LDA count
SUB one
STO count
BRZ endsq3
BR loop3 #end squaring c
endsq3 LDA total
STO f #stores c*c in f
OUT
SUB total
STO total
LDA d #begin check a^2 + b^2 = c^2
ADD e
SUB f
BRZ true
LDA count
OUT #FALSE output 000
HLT
true LDA one
OUT #TRUE output 001
HLT
a DAT
b DAT
c DAT
d DAT
e DAT
f DAT
temp DAT
total DAT 000
one DAT 001
count DAT 000
如果a,b,c形成一个毕达哥拉斯三元组或000,如果没有,程序将输出001。但是,如果发生溢出,即输入超过LMC 3位数限制,它也需要输出002。
我知道代码适用于检查a,b,c是毕达哥拉斯三元组。但是,我需要一些检查溢出的方法(LMC只接受3位数值)。为了使这更难,我正在使用的LMC版本没有溢出标志。我的想法是检查c> 31,因为大于31的任何值在平方时将大于1000,并以某种方式检查是否a^2 + b^2> 1000.为了进一步复杂化,LMC仅具有99个内存地址来存储数据和指令,而我只剩下5-6个。无论如何,我可以简化上述代码以减少程序指令占用的内存量。我原本以为我可以使用一个循环来进行平方处理,但我不确定每次我如何分支以将结果保存在不同的变量中。
任何帮助将不胜感激。
UPDATE: 这里是插入排序LMC代码工作
inloop IN # get a number
STO tmp
SUB range #check input < 31
BRP error
LDA tmp
SUB C# bigger than the biggest so far?
BRP storeC
LDA b
BRZ storeB # if empty, use b
LDA tmp # must use a
STO a
BR minus
storeB LDA tmp
STO b
BR minus
storeC LDA b
BRZ fillB # if empty, use b
BR fillA # otherwise, use a
fillB LDA c
STO b
LDA tmp
STO c
BR minus
fillA LDA c
STO a
LDA tmp
STO c
BR minus
minus LDA incount
SUB one
BRZ next
STO incount
BR inloop
next LDA a
OUT
LDA b
OUT
LDA c
OUT
HLT
error LDA overflow
OUT
HLT
range DAT 031
a DAT 000
b DAT 000
c DAT 000
tmp DAT
overflow DAT 002
incount DAT 003
one DAT 001
谢谢。我仍然不确定如何创建循环,以便每次输出结果到不同的内存地址? – JC2188 2014-11-04 23:14:33
问题是,您必须将项目插入适当的位置,这就是插入排序的工作方式。 – Jester 2014-11-04 23:40:48
我明白插入排序的作用,但我不知道如何使用LMC代码实现它。我已经看过一些汇编代码的插入排序,但我不知道汇编,或如何使用单个寄存器,而不是LMC – JC2188 2014-11-05 00:41:38