我尝试使用以下代码,但答案是错误的。它应该是55但我得到10.任何帮助人员?
main:
# initialize values to 3 registers
addi $a0,$zero,10
jal sum # call method
# Print out the summation upto 10
li $v0,1 # print integer
add $a1,$v0,$zero #load return value into argument
syscall
li $v0,10 # Exit
syscall
sum:
addi $sp,$sp,-8 # allocate space on stack
sw $ra,0($sp) # store the return address
sw $a0,4($sp) # store the argument
slti $t0,$a0,1 # check if n > 0
beq $t0,$0,recurse # n > 0 case
add $v0,$0,$0 # start return value to 0
addi $sp,$sp,8 # pop 2 items off stack
jr $ra # return to caller
recurse:
addi $a0,$a0,-1 # calculate n-1
jal sum # recursively call sum(n-1)
lw $ra,0($sp) # restore saved return address
lw $a0,4($sp) # restore saved argument
addi $sp,$sp,8 # pop 2 items off stack
add $v0,$a0,$v0 # calculate n + sum(n-1)
jr $ra # return to caller
答案 0 :(得分:0)
在$v0
中存储1之后,您正在将总和从$a1
移动到$v0
。
此外,您将总和存储在$a1
中,而$a0
是要打印的寄存器..
add $a1,$v0,$zero #load return value into argument
^ HERE
这应该解决它。
add $a0,$v0,$zero #load return value into argument
li $v0,1 # print integer
syscall