1

下面是我拥有的代码,它确实有效。它输入并存储用户键入的数字(只能是 3 或 4 个数字的列表)。

然而,这真的很长,使用数组索引会少很多代码和使用更少的寄存器,但我不确定如何做到这一点。我需要在 source2 周围加上括号以使其被索引吗?

    # Entering the user's numbers

# Prompt user to enter their numbers
  la $a0, number            # load the address of number into $a0
  li $v0, 4             # 4 is the print_string syscall
  syscall

# Declare an array
la $t3, array           # load address of array into $t3
li $t4, 0           # index value 0 is the start of the memory address of the array
mul $t5, $t4, 4         # multiply index value by 4 because each element is four bytes
add $t5, $t3, $t5       # add base address of array to index value into $t5

# Get the first number from the user, put into $t1
li $v0, 5           # load syscall read_int into $v0
syscall             # make the syscall
move $t1, $v0           # move the number read into $t1
sw $t1, 0($t5)          # store number held in $t1 into memory address location $t5

# Get the second number from the user, put into $t2 and store in array
li      $v0, 5              # load syscall read_int into $v0
syscall                     # make the syscall
move $t1, $v0                           # move the number read into $t1
add $t5, $t5, 4                         # add 4 bytes to go to the next position in the array
sw $t1, 0($t5)          # store number into memory address location of $t5

# Get the third number from the user, put into $t3
li $v0, 5               # load syscall read_int into $v0
syscall                     # make the syscall
move $t1, $v0           # move the number read into $t1
add $t5, $t5, 4         # add 4 bytes to go to the next position in the array
sw $t1, 0($t5)          # store number into memory address location of $t5

# Branches to L3 if user chose to enter only three numbers
beq $t0, 3, L3          # if content in $t0 = 3, branch to L3

# Get the fourth number from the user, put into $t4
li $v0, 5               # load syscall read_int into $v0
syscall                 # make the syscall
move $t1, $v0           # move the number read into $t1
add $t5, $t5, 4         # add 4 bytes to go to the next position in the array
sw $t1, 0($t5)          # store number into memory address location of $t5

# Branches to L3 if user chose to enter only four numbers
beq $t0, 4, L3          # if content in $t0 = 4, branch to L3

编辑:到目前为止我有这个....虽然它不起作用 - 它不接受用户输入的整数

    loop:
    lw $t2, 0($a0) # load array element from memory
    addi $t2, $t2, 1 # increment element
    sw $t2, 0($a0) # write back to memory
    addi $a0, $a0, 4 # increment array pointer by 4 (word = 4 bytes)
    addi $t1, $t1, 1 # increment loop counter by 1
    blt $t1, $t0, loop # loop, if necessary

它不工作是因为我已经有数字了$t0吗?我问用户他们想要多少个列表(3 或 4 并且存储在 中$t0),然后我要求他们输入他们的数字列表(我需要将其放入数组中)。如果我再把这个数组也放在$t0. 当提示说出他们想要的列表长度时,它会覆盖用户首先输入的数字吗?

4

0 回答 0