1

完成SPIM汇编语言程序loop2.s。程序将计算“数字”中小于或等于 1000 的元素的总和。

我试图编写代码,但是输出即将到来,而我需要它是 11

程序名称:loop2.s

  • 将计算数组“numbers”中值小于或等于 1000 的所有元素的总和。
  • “numbers”是一个包含 5 个整数元素的数组。
  • “count”保存“numbers”中元素的数量。

  • 输出格式必须为“sum = 11”

t0 - 依次指向数组元素 t1 - 包含元素计数

t2 - 包含总和

t3 - 依次来自数组“numbers”的每个单词

#################################################
#                                               #
#               text segment                    #
#                                               #
#################################################

        .text
        .globl __start
__start:                # execution starts here


#   Put your answer between dashed lines.
#
#------------------Your code starts next line---------------
  la $t0, numbers
   lw $t1, count
   li $t2, 0

   process:
       lw $t3, ($t0)           # load word from the array
       add $t2, $t2, $t3       # add it to sum
       add $t0, $t0, 4           # increment the pointer / get the next element of the array
       sub $t1, $t1, 1           # decrement the counter
       beqz $t1, done           # if counter = 0, then it's done
       j process

   done:
       la $a0, ans1
       li $v0, 4  
       syscall

       move $a0, $t2
       li $v0, 1
       syscall

       la $a0, endl
       li $v0, 4
       syscall

       li $v0, 10
       syscall
#-----------------Your code ends above this line----------------

    la $a0,endl # syscall to print out
    li $v0,4    # a new line
    syscall 

    li $v0,10   # Exit
    syscall     # Bye!


#################################################
#                                               #
#               data segment                    #
#                                               #
#################################################

        .data
    numbers:    
        .word 3,2000,2,6,3000
    count:  .word 5

    ans1:   .asciiz "sum = "
    endl:   .asciiz "\n"       

##
##  end of file loop2.s
4

1 回答 1

0

您需要添加代码来检查该值是否 <= 1000(或 > 1000),以便(或不)将数字添加到 $t2。

process:
   lw $t3, ($t0)           # load word from the array

   # check if > 1000, and if it is, jump to don't_add (ie: skip the adding to sum)
   bgt $t3, 1000, dont_add


   add $t2, $t2, $t3       # add it to sum
dont_add:    
   add $t0, $t0, 4         # increment the pointer / get the next element of the array
   sub $t1, $t1, 1         # decrement the counter
   beqz $t1, done          # if counter = 0, then it's done
   j process

done:
于 2019-06-14T12:59:15.190 回答