我试图将这段代码转换成 MIPS 指令。假设a在$a0中,b在$a1中,n在$a2中,结果在$v0中,结束 程序,调用“jr $ra”返回子程序调用者
int fib_iter(int a, int b, int n) {
if (n == 0)
return b;
else
return fib_iter(a+b, a, n-1);
为简单起见,我们忽略这个堆栈帧 这是我转换的 MIPS 代码:
bne $a1, $zero, ELISEIF // if b != 0 go to ELSEIF
lw $v0, $0($a1) // load b to result if n == 0
j DONE // done
ELSEIF:
lw $at, $0($a0) // temp = a
add $a0, $a0, $a1 // a = a + b
add $a1, $zero, $zero // clear b
lw $a1, $0($at) // b = a
sub $a2, $a2, $1 // n = n - 1
jr $ra // call the subroutine caller
Done:
what to put??
请指出我的错误(因为我是新手,可能有很多错误)
谢谢你花时间帮助我,我很感激
最佳答案
lw $v0 $0($a1)
将执行 $v0 = $a1[0]
而不是 $v0 = $a1
。要执行后者,请使用 mv $v0 $a1
。
$at
也为 pseudoinstructions 保留在 MIPS 中。我的意思是它们被伪指令修改了。所以,除非你确定你没有使用任何伪指令,否则不要使用它。 $t1 到 $t7
是临时寄存器。使用其中任何一个。
正确代码如下
FIB:
bne $a2, $zero, ELSE // if n != 0 go to ELSE
mv $v0, $a1 // load b to result if n == 0
jr $ra // end of recursion, so call the subroutine caller
ELSE:
mv $t0, $a0 // temp = a
add $a0, $a0, $a1 // a = a + b
mv $a1, $t0 // b = a
addi $a2, $a2, -1 // n = n - 1
j FIB // call FIB recursively
关于C语言转MIPS。斐波那契数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009303/