1
        INP
        STA numOne
        OUT
        INP
        STA numTwo
        OUT
        LDA numOne
        ADD numTwo
        STA numThree
        OUT
        LDA numTwo
        ADD numThree
        STA numFour
        OUT
        LDA numThree
        ADD numFour
        STA numFive
        OUT
        LDA numFour
        ADD numFive
        STA numSix
        OUT
        LDA numFive
        ADD numSix
        STA numSeven
        OUT
        LDA numSix
        ADD numSeven
        STA numEight
    OUT
        LDA numSeven
        ADD numEight
        STA numNine
    OUT
        LDA numEight
        ADD numNine
        STA numTen
        OUT
numOne  dat
numTwo  dat
numThree dat
numFour dat
numFive dat
numSix  dat
numSeven dat
numEight dat
numNine dat
numTen dat

I am using the following code in Little Man Computer to output the first 10 Fibonacci sequence terms, however I need to make a loop out of this, which will let me control the amount of iterations I want to be outputted.

From my understanding, I'd guess I would have to input 3 numbers - two of them being the first Fibonacci sequence terms, the third one being the amount of iterations I want to be outputted. But how can I achieve this?

4

1 回答 1

2

斐波那契数列可以通过以下方式在 LMC 中打印:

      INP
      STO   n     #number of terms
      LDA   one
      OUT

loop  LDA   fib     #THE MAIN LOOP THAT PRINTS FIBONACCI NUMBERS
      STO   temp2
      ADD   temp
      STO   fib
      LDA   temp2
      STO   temp
      BR    check

check LDA   n         #LOOP TO KEEP A TRACK OF NUMBER OF TERMS
      BRZ   halt
      SUB   one
      STO   n
      BRZ   halt
      LDA   fib
      OUT
      BR    loop

halt  HLT        
n     DAT   000
fib   DAT   001
temp  DAT   001
temp2 DAT   000
one   DAT   001

说明:程序首先要求输入 n,即要打印的词条数。然后循环开始运行 - 它将打印变量 fib 的默认值,该值已设置为 1。fib 的值存储在另一个变量 temp2,变量 temp 用于记录 fib 之前的值,以便正确添加数字,得到正确的序列。随着项数的增加,循环控制 fib、temp 和 temp2 的值。

然后程序检查是否已打印所需的术语数并递减 n 的值。如果 n = 0,则表示已达到所需的术语数并且程序停止。如果 n 不为零,则循环继续直到 n=0。

**虽然我可能有更有效的方法,但是这个方法可以正常工作并且使用的邮箱数量非常少,这使得它非常有效。

于 2016-06-01T21:51:33.913 回答