0

有人可以给我一些关于如何将我的代码变成从 main 调用的子例程的建议吗?

.data
inputOne: .word 2 # Value 1
inputTwo: .word 3 # Value 2
counter: .word 0  # Adds the amount of times that we go through the loop
sum: .word 0      # Where the result of the addition goes

.text
main:
lw $t2, inputOne  # Load 2 into register t2
lw $t3, inputTwo  # Load 3 into register t3
lw $t4, counter   # Load 0 into register t4
lw $t5, sum       # Load 0 into register t5
topOfLoop:        # Start of the loop
beq $t4, $t2, bottomOfLoop  # Until t4 is equal to t2, the loop will continue
addi $t5, $t5, 3  # Adds 3 to register t5 ( Sum) 
addi $t4, $t4, 1  # Adds 1 to register t5 (Counter)
j topOfLoop       # Jumps to the top of the loop
    bottomOfLoop:     # End of the loop 
    sw $t5, sum       #Storing the value in $t5 into sum
4

1 回答 1

1

使用 jal 和 jr $ra:

.data
inputOne: .word 2 # Value 1
inputTwo: .word 3 # Value 2
counter: .word 0  # Adds the amount of times that we go through the loop
sum: .word 0      # Where the result of the addition goes

.text
main:
lw $t2, inputOne  # Load 2 into register t2
lw $t3, inputTwo  # Load 3 into register t3
lw $t4, counter   # Load 0 into register t4
lw $t5, sum       # Load 0 into register t5

jal sub           # go to sub and store the address of the next position in $ra
li $vo, 10
syscall           #end program

sub:
topOfLoop:        # Start of the loop
beq $t4, $t2, bottomOfLoop  # Until t4 is equal to t2, the loop will continue
addi $t5, $t5, 3  # Adds 3 to register t5 ( Sum) 
addi $t4, $t4, 1  # Adds 1 to register t5 (Counter)
j topOfLoop       # Jumps to the top of the loop
    bottomOfLoop:     # End of the loop 
    sw $t5, sum       #Storing the value in $t5 into sum
jr $ra # jump to the address in $ra, as it is filled by jal

请记住:按照惯例,$t 寄存器可以由子程序更改,$s 寄存器必须在子程序结束之前由子程序恢复,$a 寄存器用于参数,$v 寄存器用于返回值。

于 2013-11-05T20:52:26.463 回答