问题描述
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