我正在尝试解决在mips中添加数组中元素的问题。
我必须插入nops或重新排列代码才能正常工作,但我无法做到。有人可以建议一些想法。感谢
答案 0 :(得分:0)
这是一种使用循环的方法,您可以通过它遍历数组并计算其所有元素的总和:
.data
newline: .asciiz "\n"
array: .word 1, 3, 5, 7, 9, 12, 14, 15, 17, 19
length: .word 10
sum: .word 0
.text
.globl main
main:
#loop through the array to calculate sum
#array's starting address
la $t0 array
#loop index, i=0 ($t1=i)
li $t1 0
#loading the length of array in register t2
lw $t2 length
#initialise sum =0
li $t3 0
sumLoop:
#get array[i]
lw $t4 ($t0)
#sum = sum+array[i]
add $t3 $t3 $t4
#updating countervariable
addi $t1 $t1 1 #i = i+1
add $t0 $t0 4 #update array address
#while i<length , traverse the loop again
#blt (branch less than) (if $t1<$t2 then go through the loop)
blt $t1 $t2 sumLoop
sw $t3 sum #save sum
#printing the sum on syscall
move $a0 $t3
li $v0 1
syscall
li $v0 10
syscall
.end main