1
嗨,我需要打印斐波那契數列的值直到第n個值(用戶輸入)。所以,如果用戶輸入3,我將不得不打印1,1,2。我必須遞歸地和迭代地執行它。我得到了迭代的一部分,但我在遞歸部分遇到了一些麻煩。在程序中,我可以打印它的值。任何幫助,將不勝感激。使用mips遞歸打印Fibonacci序列
.data
inputMsg: .asciiz "Enter number: "
iterationMsg: .asciiz "\nIterative: "
recursionMsg: .asciiz "\nRecursive: "
series: .asciiz "\nThe series is: "
space: .asciiz " "
.text
main:
la $a0, inputMsg #Print out inputMsg
li $v0, 4
syscall
li $v0, 5 #Read in integer into v0
syscall
subi $s0, $v0, 1 #s0 = v0-1
add $s7, $s0, 0 #s7 = s0
add $s3, $v0, 0 #s3 = v0-1
addi $s1, $s1, 1 #s1 = 1
addi $s2, $s2, 1 #s2 = 1
la $a0, iterationMsg #Print out text_iteration
li $v0, 4
syscall
la $a0, series #Print out series
syscall
addi $a0, $zero, 1 #a0 = 1
li $v0, 1
syscall #Prints out 1
jal iterative #Jump to iterative
la $a0, recursionMsg #Print Out Recursion text
li $v0, 4
syscall
la $a0, series #Print out Series text
syscall
add $a0, $s3, $0 #t0 = s3 = inputted val
add $s0, $0, $0
jal recursive
exit:
li, $v0, 10 #Exit Program
syscall
iterative:
beq $s0, 0, iterativeExit #if s0 = 0 then exit
subi $s0, $s0, 1 # s0 = s0
add $t0, $s2, $zero # t0 = s2(1) + 0
add $s2, $s1, $s2 # s2 = s1(1) + s2(1)
add $s1, $t0, $zero # s1 = t0(1) + 0
la $a0, space
li $v0, 4
syscall
add $a0, $s1, $zero
li $v0, 1
syscall
bnez $s0, iterative
iterativeExit:
jr $ra
recursive:
addi $sp, $sp, -4 #create/save stack
sw $ra, 0($sp)
sub $a0, $a0, 1 #minus one from inputted val (a0) till 0
beq $a0, 1, oneRec
jal recursive
jal print
lw $ra, 0($sp) #
addi $sp, $sp, 4 # decrease the stack size
jr $ra
oneRec:
li $a0, 1
li $v0, 1
syscall
addi $s0, $a0, 0
la $a0, space
li $v0, 4
syscall
jr $ra
print:
add $t0, $0, $a0
add $a0, $s0, $a0
li $v0, 1
syscall
la $a0, space
li $v0, 4
syscall
add $s0, $t0, $0
jr $ra