使用用户输入以mips迭代添加数字。我正在尝试将数字从1添加到用户输入的mips中,但输出始终为1

时间:2017-10-13 03:08:26

标签: loops mips

enter image description here

.data
prompt:.asciiz "Enter a positive integer:"
I_msg1: .asciiz "(Iterarive) Sum from 1 to "
I_msg2: .asciiz " = "
R_msg1: .asciiz "(Recursive) Sum from 1 to "
R_msg2: .asciiz " = "
NewLine: .asciiz "\n"
NewLine2:.asciiz "\n\n"
done:.asciiz "Done..."


n : .word 0
result1: .word 0
result2: .word 0

.text 

.globl main
main:

    # Make two line space
    li $v0, 4
    la $a0,NewLine2
    syscall 
    # Print message to prompt user input
    li $v0, 4
    la $a0,prompt
    syscall 
    #read user input 
    li $v0, 5
    syscall
    #store user input in variable n
    sw $v0,n 
    #___________________________________
    #print I_msg1   
    li $v0,4
    la $a0,I_msg1
    syscall

    #print user input 
    li $v0,1
    lw $a0, n
    syscall

    #call iterative function 
    lw $a0,n
    jal ItrSum
    sw $v0, result1

    #Display I_msg2 
    li $v0, 4
    la $a0,I_msg2
    syscall 
    #print result of iterative sum
    li $v0,1
    lw $a0, result1
    syscall

    li $v0, 4
    la $a0,NewLine
    syscall 
    #______________________________

    #Exit 
    li $v0,10
    syscall

.globl ItrSum
    addi $sp, $sp, -4
    sw $s0,($sp)
    move $s0,$a0 #store value of n in $s0
ItrSum:
    beq $s0,$zero,end #if n = 0 end loop
    subi $t0,$s0,1 # find n-1 and store in new location t1
    add $t0,$s0,$t0 # n+(n-1)
    subi $s0,$s0,1  # decrement original  n 
    j ItrSum  #repeat

    end:
    add $v0, $s0,$v0 #store result in $v0
    lw $s0, ($sp)   
    addi $sp, $sp, 4 
    jr $ra

1 个答案:

答案 0 :(得分:0)

add $v0, $s0,$v0 #store result in $v0

$s0 + $v0显然不会保留你的结果。 $s0是您的循环计数器,它将为0.而$v0将为1,因为您上次使用它时是打印用户输入。对我来说就像你想要move $v0, $t0

您的代码有其他问题。例如,ItrSum标签位于循环开始的位置,而不是函数开始的位置。更好的方法是:

ItrSum:
    addi $sp, $sp, -4
    sw $s0,($sp)
    li $v0,0      # result
    move $t0,$a0  # $t0 = n
sum_loop:       
    beq $t0,$zero,end  # if n = 0 end loop
    addu $v0,$v0,$t0   # result += n
    addi $t0,$t0,-1    # n -= 1
    j sum_loop         # repeat
end:
    lw $s0, ($sp)   
    addi $sp, $sp, 4 
    jr $ra