【问题标题】:storing array from user and accessing it从用户存储数组并访问它
【发布时间】:2015-06-15 20:13:12
【问题描述】:

我必须根据用户输入创建一个 int 数组,对整数求和,然后输出总和和数组本身。

我的代码正确计算了总和,但我无法输出列表。它只打印出最后一个数字和零,然后在 PRINTLIST 中陷入无限循环。

我认为问题在于访问数组。谁能帮帮我?

    .data   

intro:  

    .asciiz "Enter numbers\n"

sum:    

    .asciiz "\nSum= "

list:

    .asciiz "\nList looks like: "       

array:  

    .space 400
    .text

main:

    li  $t1,0       #count
    la  $a1,array   

    li  $v0,4
    la  $a0,intro   
    syscall

    j   INPUT
    jr  $ra

GETLIST:

    li   $v0, 5     
    syscall

    move $t0,$v0    
    bltz $t0,SUM    #leave if negative

    add $t2,$t2,$t0 
    add $t1,$t1,1   #increment counter

    sw  $v0,0($a2)  #store in array
    add $a0,$a0,4   

    move $t5,$t2    

    j   GETLIST     

SUM:

    li  $v0,4
    la  $a0,sum
    syscall

    li  $v0,1
    move    $a0,$t5     #sum to a0
    syscall

    li  $v0,4
    la  $a0,list
    syscall

    add $t1,$t1,-1
PRINTLIST:

    lw  $t0,0($a1)
    add $a1,$a1,4
    add $t1,$t1,-1

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

    bltz    $t1,NEXT    #leave when end of list 
    j   PRINTLIST

【问题讨论】:

    标签: arrays assembly input mips


    【解决方案1】:

    我发现的一些错误是:

    在GETLIST中:

    sw  $v0,0($a2)  #store in array
    add $a0,$a0,4   #next number    <= instead write 'add $a2,$a2,4' if you want don't want to overwrite it.
    

    打印列表中的问题也是您要添加$a2 以将数字存储在数组中。但是,您忘记将$a2 的值重新分配给数组的初始地址。因此可以通过以下方式解决:

        add $t1,$t1,-1
        la $a2, array        <= line added
    PRINTLIST:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-27
      • 2019-03-19
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2013-09-07
      • 2013-12-22
      • 2013-04-30
      相关资源
      最近更新 更多