问题
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
回答1:
You are printing a memory address, not the result of your calculation.
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.
Also, your add instruction does not use the result from the previous recursive call. It instead uses the two argument registers.
Finally, syscall 1 prints the number in $a0, not $a1
So:
move $a2, $v0should bemove $a1, $v0(line 10)move $a1, $v0should bemove $a0, $v0(line 18)add $a1, $v0, $zeroshould beadd $a0, $v0, $zero(line 22)add $v0, $a2, $a1should beadd $v0, $v0, $a1(line 46)
来源:https://stackoverflow.com/questions/55859580/recursive-product-mips