[英]How to find the greatest of more than two input numbers
I was able to write an LMC program which finds the greater value of two input values.我能够编写一个 LMC 程序,它可以找到两个输入值中较大的值。 But how do I modify it to find the greatest value of any number of input values, not only two?
但是如何修改它以找到任意数量的输入值中的最大值,而不仅仅是两个?
Below is my code:下面是我的代码:
START INP
STA NUM1
INP
STA NUM2
LDA NUM1
SUB NUM2
BRP Positive
LDA NUM2
OUT
HLT
Positive LDA NUM1
HLT
NUM1 DAT
NUM2 DAT
Let NUM1 be the maximum so far , and make a loop to read the next input into NUM2.令 NUM1 成为迄今为止的最大值,并进行循环以将下一个输入读入 NUM2。 If the comparison shows that next input is greater, then update NUM1, else not.
如果比较显示下一个输入更大,则更新 NUM1,否则不更新。
With this method it is probably better to rename NUM1 to MAX, NUM2 to just NUM.使用这种方法,最好将 NUM1 重命名为 MAX,将 NUM2 重命名为 NUM。
You should also determine what will be the indication that all input has been provided.您还应该确定已提供所有输入的指示。 One way to do that is to agree that the user must input a specific value to mark the end of the input.
一种方法是同意用户必须输入一个特定的值来标记输入的结束。 Obviously that means that that special value cannot be part of the input itself.
显然,这意味着该特殊值不能成为输入本身的一部分。
Here is how it would look if that terminating value is 0:如果该终止值为 0,它的外观如下所示:
#input: 5 2 8 4 5 0 START INP BRZ OUTPUT STA MAX LOOP INP BRZ OUTPUT STA NUM LDA MAX SUB NUM BRP LOOP ; input was not greater LDA NUM STA MAX ; input was greater BRA LOOP OUTPUT LDA MAX OUT HLT NUM DAT MAX DAT 0 <script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.7/lmc.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.