Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

stack - the answer is always wrong in this MIPS recursion . got 10, supposed to be 55

This code is supposed to print the sum of numbers from 10 to 0. It should be printing 55, but is printing 10 instead. Can you help me figure out where it's going wrong?

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  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Functions return their value in $v0; the print integer syscall expects its argument in $a0.
You need to move $a0 to $v0 before you do the print, otherwise you'll be printing whatever happened to be in $a0 (which in the case is the last value that you recursively added; i.e. 10).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...