我必须编写一个MIPS代码来对系列1 + 5 + 9 + ... + N求和,在我应该使用最少数量的寄存器来实现MIPS代码的约束下。
这是我的解决方案。如果你能指出任何错误,那就太好了。
High-level code:
int count = 1;
int sum = 1;
while(count<N){
count = count + 4;
sum = sum + count;
}
Associate variable 'count' with register $t0 and
variable 'sum' with register $s0.
Equivalent MIPS code:
addi $t0, $zero, 1
addi $s0, $zero, 1
Loop: slti $t2, $t0, N
beq $t2, $zero, Exit
addi $t0, $t0, 4
addi $s0, $s0, $t0
j Loop
Exit:
答案 0 :(得分:1)
您需要一个寄存器来保存实际总和。如果N是硬编码的,我会做这样的事情(未经测试的代码);
addi $t0, $zero, 0 ; Sum
addi $t1, $zero, 1 ; Counter
Loop:
slti $t2, $t1, N + 1 ; Exit if $t1 > N
beq $t2, $zero, Exit
add $t0, $t0, $t1 ; $t0 = $t0 + $t1
addi $t1, $t1, 4 ; $t1 += 4
j Loop
Exit: ; $t0 contains the sum here