Search code examples
assemblymipseclipse-mars

Always getting back same Integer


Got a homework question asking me to take two user inputs, compare them, and input them into an equation.

This is my template: ($t1 + 5) - ($t2 * 2) = result

However, I seem to be getting a return value of 5 (or 05) every time I run it. I'm not too sure what I'm doing wrong.

Here's the code:

.text

# First Input - Saved to $t1
la  $a0, input
li  $v0, 4
syscall

li  $v0, 5
move    $a0, $t1
syscall

# Second Input - Saved to $t2
la  $a0, input2
li  $v0, 4
syscall

li  $v0, 5
move    $a0, $t2
syscall

# Compare the two Inputs
bgt $t1, $t2, Bigger
blt $t1, $t2, Smaller

# If the 1st is greater
# ($t1 + 5) - ($t2 * 2) = result
Bigger:
    add $t4, $t1, 5 # $t4 = $t1 + 5
    mul $t5, $t2, 2 # $t5 = $t2 * 2
    sub     $t7, $t4, $t5   # $t7 = $t4 - $t5
    syscall

    li  $v0, 1
    move    $a0, $t7
    syscall

    li  $v0, 10
    syscall

# If the 1st is smaller
Smaller: 
    add $t4, $t2, 5 # $t4 = $t2 + 5
    mul $t5, $t1, 2 # $t5 = $t1 * 2
    sub     $t7, $t4, $t5   # $t7 = $t4 - $t5

    li  $v0, 1
    move    $a0, $t7
    syscall

    li  $v0, 10
    syscall


.data

input:  .asciiz "Enter the First Integer: "

input2: .asciiz "Enter the Second Integer: "

Halt:   li  $v0, 10
        syscall

Any help? Thanks!


Solution

  • The read_int syscall simply needs the function code 5 in $v0 and returns the input value in there too. So instead of:

    li  $v0, 5
    move    $a0, $t1
    syscall
    

    You should do:

    li  $v0, 5
    syscall
    move    $t1, $v0
    

    Similarly for the other number of course.

    Incorporating @markgz's comment about $t registers being caller saved, the whole code could look like:

    .text
    # First Input - Saved to $t1
    la  $a0, input
    li  $v0, 4
    syscall
    
    li  $v0, 5
    syscall
    move    $s0, $v0  # save to $s0
    
    # Second Input - Saved to $t2
    la  $a0, input2
    li  $v0, 4
    syscall
    
    li  $v0, 5
    syscall
    move    $t1, $s0 # restore 1st number
    move    $t2, $v0
    
    # Compare the two Inputs
    bgt $t1, $t2, Bigger
    blt $t1, $t2, Smaller
    
    # If the 1st is greater
    # ($t1 + 5) - ($t2 * 2) = result
    Bigger:
        add $t4, $t1, 5 # $t4 = $t1 + 5
        mul $t5, $t2, 2 # $t5 = $t2 * 2
        sub     $t7, $t4, $t5   # $t7 = $t4 - $t5
    
        li  $v0, 1
        move    $a0, $t7
        syscall
    
        li  $v0, 10
        syscall
    
    # If the 1st is smaller
    Smaller:
        add $t4, $t2, 5 # $t4 = $t2 + 5
        mul $t5, $t1, 2 # $t5 = $t1 * 2
        sub     $t7, $t4, $t5   # $t7 = $t4 - $t5
    
        li  $v0, 1
        move    $a0, $t7
        syscall
    
        li  $v0, 10
        syscall
    
    
    .data
    
    input:  .asciiz "Enter the First Integer: "
    
    input2: .asciiz "Enter the Second Integer: "
    
    Halt:   li  $v0, 10
            syscall