我一直在使用StackOverflow帮助完成家庭作业,但这次我找不到答案。
我以为我的一切都运转了,但是当我改变阵列中的元素时,它什么都没做。
在我的程序中,我必须初始化数组,打印出数组,然后调用一个方法来对数组中的元素求和。我必须传递两个参数,一个是数组的基地址,另一个是数组的长度。
这是我现在的代码。它只是在整个长度上打印1,并忽略数组中的实际内容。
.data
array: .word 2, 4, 6, 8, 10
newline:.asciiz "\n"
space: .asciiz " "
.text
la $a0, array # $a0 -----> array
li $a1, 5 # $a1 -----> length of array
jal SUM # calls sum
j end
SUM:
move $t0, $a0 # $t0 -----> $a0 ( array )
move $t1, $a1 # $t1 -----> $a1 ( length of array )
li $t2, 0 # $t2 -----> 0 ( i = 0 )
li $t3, 0 # $t3 -----> 0 ( sum = 0 )
loop:
beq $t1, $t2, endloop # checks to see if length of array == i
mul $t4, $t2, 4 # multiply i by 4, so offset stays with array in loop
add $t4, $t0, $t4 # puts memory address of array into $t3 so we get array [i]
sw $t4, ($t4) # loads memory address of array[i] into $t3
addi $t2, $t2, 1 # i++;
add $t3, $t3, $t2 # sum = sum + array [i];
li $v0, 1 # prints value
move $a0, $t2 # at
syscall # array[i]
li $v0, 4 # prints
la $a0, space # a
syscall # space
j loop
endloop:
li $v0, 4 # prints
la $a0, newline # a
syscall # new line
li $v0, 1 # prints value
add $a0, $t3, $0 # of
syscall # sum
jr $ra
end:
对不起评论的格式,我无法弄清楚如何对齐它们。
答案 0 :(得分:0)
您有几个错误:
sw $t4, ($t4) # loads memory address of array[i] into $t3
这与评论不符。此外,您不应该将值加载到$ t3中,因为您将覆盖总和(# $t3 -----> 0 ( sum = 0 )
)。我会使用$ t5,所以应该是这样的:
lw $t5, ($t4)
此外,您还要将索引添加到总和而不是实际的数组值中:
add $t3, $t3, $t2
使用LW进行先前的校正,应该是:
add $t3, $t3, $t5
最后你还要打印索引而不是值:
move $a0, $t2
应该是
move $a0, $t5
PS:使用分支循环,而不是跳转。跳转通常用于函数调用或远程调用。
PS2:结束程序使用系统调用10.
PS3:你也应该阅读MIPS delay slot。