问题描述
我对代码进行了一些更改,但它仍在打印一个 9 位数字.不知道这里发生了什么.当我输入 2 * 3 时,它输出 268501017.我很难找出如何从寄存器中获取结果并打印出来.
I made some changes to the code, but it is still printing a 9digit number. Not sure what's going on here. When I type in 2 * 3, it outputs 268501017. Im having a hard time find out how to get the result from the register and print it.
main:
#prompt 1
li $v0, 4 # Print the String at Label "Input"
la $a0, num1
syscall
li $v0, 5
syscall
move $a2, $v0
#prompt 2
li $v0, 4 # Print the String at Label "Input"
la $a0, num2
syscall
li $v0, 5 # Read integer from user
syscall
move $a1, $v0 # Pass integer to input argument register $a0
jal multiply
add $a1, $v0, $zero
li $v0, 1
syscall
li $v0, 10
syscall
multiply:
bne $a1, 0, recurse
move $v0, $a1
jr $ra
recurse:
sub $sp, $sp, 12
sw $ra, 0($sp)
sw $a0, 4($sp)
sw $a1, 8($sp)
addiu $a1, $a1, -1 #product(x, y-1)
jal multiply
lw $a1, 4($sp)
add $v0, $a2, $a1
lw $ra, 0($sp)
addi $sp, $sp, 12
jr $ra
推荐答案
您打印的是内存地址,而不是计算结果.
You are printing a memory address, not the result of your calculation.
这是由于重用了 $a0
,它仍然保存着 num1
的地址.如果 multiply
只需要这两个操作数,您应该只将这两个操作数存储在 $a0
和 $a1
中.
This is due to reusing $a0
which is still holding the address of num1
. You should store just the two operands in $a0
and $a1
if that is all that is needed for multiply
.
此外,您的 add 指令不使用上一次递归调用的结果.它改为使用两个参数寄存器.
Also, your add instruction does not use the result from the previous recursive call. It instead uses the two argument registers.
最后,系统调用 1 打印 $a0
中的数字,而不是 $a1
Finally, syscall 1 prints the number in $a0
, not $a1
所以:
move $a2, $v0
应该是move $a1, $v0
(第 10 行)move $a1, $v0
应该是move $a0, $v0
(第 18 行)add $a1, $v0, $zero
应该是add $a0, $v0, $zero
(第 22 行)add $v0, $a2, $a1
应该是add $v0, $v0, $a1
(第 46 行)
move $a2, $v0
should bemove $a1, $v0
(line 10)move $a1, $v0
should bemove $a0, $v0
(line 18)add $a1, $v0, $zero
should beadd $a0, $v0, $zero
(line 22)add $v0, $a2, $a1
should beadd $v0, $v0, $a1
(line 46)
这篇关于递归乘积mips的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!