Вопрос

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  
Это было полезно?

Решение

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).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top