如何解决MIPS递归功能无法正常工作
fact: #a1 = n a2 = res
addi $t1,$zero,1
beq $a1,$t1,end # if n == 1 return res
#else
mul $a2,$a2,$a1
subi $a1,$a1,1
jal fact
end:
sb $a2,res
jr $ra
问题是,仅当我编写j fact
而不是jal fact
时,此代码才有效,而jal fact
出于某种原因,代码将无限运行。
解决方法
fact: #a1 = n a2 = res
addi $t1,$zero,1
beq $a1,$t1,end # if n == 1 return res
#else
addi $sp,$sp,8
sw $a1,0($sp) # in the top of the stack store the argument you called fact
sw $ra,4($sp) # ra holds the return adress ( I do not know whether you know it)
mul $a2,$a2,$a1
subi $a1,$a1,1
jr $ra
jal fact
lw $a1,0($sp) # load the value from memory adress that the top stack pointer shows to back to the register a1
lw $ra,4($sp)
addi $sp,8 # delete current top,top-1 from the stack
jr $ra
end:
sb $a2,res
jr $ra
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。