使用while循环的MIPS中的Fibonacci序列

时间:2013-09-20 21:04:49

标签: assembly mips

我正在尝试编写一个程序,允许用户找到第n个斐波那契序列。我是MIPS的新手,但我似乎无法让它工作。这让我感到困惑。

    .data
    msg: .asciiz "Please enter a number to calculate the fibonnaci sequence for"
    equalsOne: .asciiz "The answer is 1"
    equalsTwo: .asciiz "The answer is 2"
    answer: .asciiz "The answer is "


.text
    addi $v0, $zero, 4  #Set $v0 to 4 (Print String)
    la $a0, msg         #Set memory address of msg to $a0
    syscall
    addi $v0, $zero, 5  #Set $v0 to 5 (Read Integer)
    syscall
    add $t0, $zero, $v0 #Store input integer in $t0
    beq $t0, 1, equals1 #If input integer == 1, go to equals1 
    beq $t0, 2, equals2 #If input integer == 2, go to equals2
    addi $t1, $zero, 1  #Stores 1 in register $t1
    addi $a1, $zero, 1  # $a1 = currentNumber
    addi $a2, $zero, 1  # $a2 = oldNumber

fib:    slt $t2, $a1, $t0   #While $a1 < $t0
    bne $t2, 1, exit
    add $a3, $a1, $a2   # $a3 = nextNumber = currentNumber + oldNumber
    add $a2, $a1, $zero #Set oldNumber = currentNumber
    add $a1, $a3, $zero #Set currentNumber = nextNumber
    j fib

equals1: la $a0, equalsOne
    addi $v0, $zero, 4
    syscall

equals2: la $a0, equalsTwo
    addi $v0, $zero, 4
    syscall

exit: addi $v0, $zero, 1    #Print integer
    add $a1, $a1, $zero #Print nextNumber
    syscall

1 个答案:

答案 0 :(得分:2)

系统调用1的参数进入$a0。所以这一行:

add $a1, $a1, $zero #Print nextNumber

应更改为:

add $a0, $a1, $zero #Print nextNumber

请注意,您将得到的是最小的斐波那契数大于或等于N 。如果您真正想要的是N:th斐波纳契数,则必须更改循环退出条件,以便迭代N次,而不是像{H}那样达到某个值。