-1

我正在尝试编写一个程序,允许用户 find 找出第 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
4

2 回答 2

2

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

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

应改为:

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

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

于 2013-09-20T23:35:02.530 回答
-1

这是我针对您的问题的代码,它可以正常工作:

addiu $a1,$0,1

addiu $a2,$0,1

addiu $t0,$0,2

beq $a0,$a1,exit1

beq $a0,$t0,exit1

jal fibonacci

addu $s0,$0,$v0

j done

fibonacci :

    addu $a3, $a1, $a2   # $a3 = nextNumber = currentNumber + oldNumber

    addu $a2, $a1, $zero #Set oldNumber = currentNumber

    addu $a1, $a3, $zero #Set currentNumber = nextNumber

    addiu $t0,$t0,1

    bne $t0,$a0,end

    addu $v0,$0,$a3

    jr $ra

    end: 

    j fibonacci

   exit1:

        addiu $s0,$0,1

        j done

     done:
于 2016-04-08T09:08:43.353 回答