递归乘积mips [英] Recursive product mips

查看:65
本文介绍了递归乘积mips的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对代码进行了一些更改,但它仍在打印一个 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

所以:

  1. move $a2, $v0 应该是 move $a1, $v0(第 10 行)
  2. move $a1, $v0 应该是 move $a0, $v0(第 18 行)
  3. add $a1, $v0, $zero 应该是 add $a0, $v0, $zero(第 22 行)
  4. add $v0, $a2, $a1 应该是 add $v0, $v0, $a1(第 46 行)
  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)

这篇关于递归乘积mips的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆