MIPS 求和函数
MIPS findSum function
我正在尝试使用 MIPS 程序集实现 findSum 函数。从第二个元素开始,它给出了错误的总和,我不知道为什么。以下是代码:
.data
myArray: .word 36 56 8 99 54 3 2 9 54 13
myArraySize: .word 10
sumMsg: .asciiz "\nThe sum is "
.text
.globl main_
main_:
jal findSum #Call the procedure to find the sum of myArray
la $a0, sumMsg #Output the message
li $v0, 4
syscall
addi $a0, $s0, 0 #Output the result
li $v0, 1
syscall
findSum:
lw $t3, myArraySize # t3 is array size
addi $a0, [=12=], 0 # a0 is sum, set it to 0
addi $t0, [=12=], 0 # t0 is count, set it to 0
lw $t1, myArray # t1 is array element
foreach: add $a0, $a0, $t1 # update sum to sum+thisElement
addi $t1, $t1, 4 # move to next element
addi $t0, $t0, 1 # count += 1
slt $t2, $t0, $t3
bne $t2, $zero, foreach # if this one is not last one, do for next one
addi $s0, $a0, 0 # store sum to s0
jr $ra
findSum:
addi $t0, [=10=], 0 # t0 is sum, set to 0
addi $t1, [=10=], 0 # t1 is count, set to 0
addi $t2, [=10=], 0 # t2 is temp, set to 0
addi $t3, [=10=], 10 # t3 is 10
la $a0, myArray # a0 is array element
foreach:
lw $t2, 0($a0) # save this element in t2
add $t0, $t0, $t2 # update sum
addi $t1, $t1, 1 # update count
addi $a0, $a0, 4 # move to next element
slt $t4, $t1, $t3 # if count < 10, store result in t4
bne $t4, [=10=], foreach
addi $s0, [=10=], 0 # init s0 to 0
addi $s0, $t0, 0 # store sum to s0
addi $v0, $t0, 0 # store sum to v0
jr $ra
我正在尝试使用 MIPS 程序集实现 findSum 函数。从第二个元素开始,它给出了错误的总和,我不知道为什么。以下是代码:
.data
myArray: .word 36 56 8 99 54 3 2 9 54 13
myArraySize: .word 10
sumMsg: .asciiz "\nThe sum is "
.text
.globl main_
main_:
jal findSum #Call the procedure to find the sum of myArray
la $a0, sumMsg #Output the message
li $v0, 4
syscall
addi $a0, $s0, 0 #Output the result
li $v0, 1
syscall
findSum:
lw $t3, myArraySize # t3 is array size
addi $a0, [=12=], 0 # a0 is sum, set it to 0
addi $t0, [=12=], 0 # t0 is count, set it to 0
lw $t1, myArray # t1 is array element
foreach: add $a0, $a0, $t1 # update sum to sum+thisElement
addi $t1, $t1, 4 # move to next element
addi $t0, $t0, 1 # count += 1
slt $t2, $t0, $t3
bne $t2, $zero, foreach # if this one is not last one, do for next one
addi $s0, $a0, 0 # store sum to s0
jr $ra
findSum:
addi $t0, [=10=], 0 # t0 is sum, set to 0
addi $t1, [=10=], 0 # t1 is count, set to 0
addi $t2, [=10=], 0 # t2 is temp, set to 0
addi $t3, [=10=], 10 # t3 is 10
la $a0, myArray # a0 is array element
foreach:
lw $t2, 0($a0) # save this element in t2
add $t0, $t0, $t2 # update sum
addi $t1, $t1, 1 # update count
addi $a0, $a0, 4 # move to next element
slt $t4, $t1, $t3 # if count < 10, store result in t4
bne $t4, [=10=], foreach
addi $s0, [=10=], 0 # init s0 to 0
addi $s0, $t0, 0 # store sum to s0
addi $v0, $t0, 0 # store sum to v0
jr $ra