Recursive product mips

走远了吗. 提交于 2019-12-11 15:03:12

问题


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:

  1. move $a2, $v0 should be move $a1, $v0 (line 10)
  2. move $a1, $v0 should be move $a0, $v0 (line 18)
  3. add $a1, $v0, $zero should be add $a0, $v0, $zero (line 22)
  4. add $v0, $a2, $a1 should be add $v0, $v0, $a1 (line 46)


来源:https://stackoverflow.com/questions/55859580/recursive-product-mips

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!