在 MIPS 中编写迭代 [英] writing iteration in MIPS

查看:95
本文介绍了在 MIPS 中编写迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 MIPS 编写这个程序来计算 2 的幂,然后将顺序幂求和为 0.例如,如果我像下面的代码一样将 4 放入 $a0 中,我希望它计算(4^2)+(3^2)+(2^2)+(1^2) 应该是 15.它应该在它达到零之前停止.这是我目前写的内容

I am writing this program in MIPS to calculate 2 to a power given by me and sum the sequential powers down to 0. For example, if I put 4 in $a0 like in the code below, I want it to calculate (4^2)+(3^2)+(2^2)+(1^2) which should come out to be 15. It should stop before it reaches zero. This is what I have written so far

main: 
addi $a0, $zero, 4    #put k in $a0 in this case 
addi $a1, $zero, 0    #put 0 in current sum
addi $v1, $v1, 0      #tally the total in $v1   
for:  
lw $10, $a0           #load k into reg $10
lw $11, $a1           #load sum into $11
    addi $10, $10, -1     #subtracts 1 from k
    li $9, 0              #sets i in for loop ($9) to 0

完成:

    li $v0, 10
    syscall

我是 MIPS 的新手,可以在完成此操作时使用很多帮助,我知道我想使用 for 循环,但我不知道如何在从 k 中减去 1 并计算和.我如何将 2 变为 k 的幂,因为我猜在 mips 中没有幂运算.在课程的这一点上,我只能使用 add、sub、and、or、slt、addi、j、beq、lw、sw 和 sll.使用 sub 时不能使用常量吗?感谢您的帮助

I'm new to MIPS and could use a lot of help on finishing this, I know I want to use a for loop, but I don't know how to go through it while subtracting 1 from k and also calculating the sum. How would I bring 2 to a power of k, because I guess there is no power operation in mips. At this point in the course I can only use add, sub, and, or, slt, addi, j, beq, lw, sw, and sll. Can you not use a constant when using sub? Thank you for any help

推荐答案

幂是乘法,乘法是和.因此,您可以编写一个通过加法进行乘法运算的函数,以及另一个通过乘法进行乘法运算的函数.例如乘法函数:

A power is a multiplication, and a multiplication is a sum. So you can write a function that does a multiplication by adding, and another function that does power by multiplicating. For example, the multiplication function:

multiply: # $a0 first factor, $a1 second factor, $v0 result of multiplication
    or $t0, $zr, $zr 
    or $t1, $a1, $a1
    or $t3, $zr, $zr
loop:
    beq $t1, $zr, end
    add $t0, $t0, $a0
    addi $t1, $t1, -1
    j loop
    nop
end:
    or $v0, $t0, $0
    jr $ra
    nop

(请注意我没有测试过这个,这不适用于负数)

(Please note I haven't tested this, and this will not work with negative numbers)

顺便说一句,您也有 MUL 指令,但我不知道您是否已经看到了.

As a side note, you have MUL instruction as well, but I don't know if you saw that already.

这篇关于在 MIPS 中编写迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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