【发布时间】:2020-08-11 18:45:21
【问题描述】:
我是 mips 的新手 这是作业的一部分,所以我想与其直接给出答案,不如指出错误的地方可能最适合我理解
目标是将这段 C++ 代码转换成 mips 汇编语言
#fib(int n)
#{
# if(n == 0)
# return 0
# else if ( n == 1)
# return 1
# else
# return fib(n-1) +fib(n-2)
#n will be stored in a0 since it is the argument
#there will be two results, fib(n-1) and fib(n-2), store in the s0 and s1, so in the stack
#return the final value in $v0
addi $s2, $zero, 10
move $a0, $s2 #move the value of n to a0 to pass the argument
jal fib
beq $zero, $zero, END
fib: #fib code
addi $sp, $sp, -12 #reserve stack space for three variable needed to store in the stack
sw $ra, 0($sp) #for return address store in stack
sw $s0, 4($sp) #for results store in stack
sw $a0, 8($sp) #for first result of fib(n-1) store in the stack
beq $a0, $zero, if0
beq $a0, 1, if1
#else if case
addi $a0, $a0, -1
jal fib
move $s0, $v0
lw $a0, 8($sp)
addi $a0, $a0, -2
jal fib
add $v0, $v0, $s0
lw $s0, 8($sp)
lw $ra, 0($sp)
addiu $sp, $sp, 12
jr $ra
if0:
lw $s0, 4($sp)
lw $ra, 0($sp)
addiu $sp, $sp, 12
li $v0, 0
jr $ra
if1:
lw $s0, 4($sp)
lw $ra, 0($sp)
addiu $sp, $sp, 12
li $v0, 1
jr $ra
END:
nop
但是,当 n = 10 时,结果并没有给我 55 存储在 v0 中的当前结果给了我 21 的值 有人可以帮我弄清楚我在哪里做错了吗? 提前致谢。
【问题讨论】:
-
你试过调试它吗?使用 MARS 或 QtSpim。
-
附注:您可以将
if (n==0) {return 0}; else if (n==1) {return 1};替换为if (n<=1) {return n}以方便自己。 -
是的,我用 mars 试过了,它没有给我任何错误。