Search code examples
mips32

Subtracting two user input numbers, with a move and display the result


I'm new to MIPS and I'm using MARS. I can't get my move right and when I execute it gives me some nuts o number. Here is what I have so far, any help would be appreciated.

.data

   message1: .asciiz "Enter the any number to subtract :"
   message2: .asciiz "\nEnter the any number to subtract :"
   n1 :      .word 0
   n2 :      .word 0
   message3: .asciiz  "\nThe subtraction of the two numbers is "

.text 
main:   
li $v0 4        #print out message1
la $a0 message1
syscall

li $v0 5        #read message1 as number1
syscall

sw $v0 n1       #store number

li $v0 4        #print out message2
la $a0 message2
syscall

li $v0 5        #read message2 as number2
syscall

sw $v0 n2       #store number

li $v0 4
la $a0 message3
syscall

lw $t0 n1
lw $t1 n2

sub $t0, $v0, $v0   #   t0 = number1 s1 - number2 s2

li $v0, 1       #   print integer
move $t0, $a0       #   move t0 to a0 

syscall         #   run

Solution

  • Your code is doing well until here sub $t0, $v0, $v0.When you subtract you should put the the result in the argument register $a0then you can use move to put that result in return register $v0 for printing.

    change them as following it will work.

    sub $t2, $t0, $t1   #   t2 = t0 - t1
    move $a0, $t2       #   copy t2 to a0
    li $v0, 1           #   print integer
    syscall             #   
    

    Another way of doing this subtraction is that you don't need .word and lwat all. As following

            .data
    
            message1: .asciiz "Enter the any number to subtract :"
            message2: .asciiz "\nEnter the any number to subtract :"
            message3: .asciiz "\nThe subtraction of the two numbers is "
    
            .text
            main:
                li $v0 4        #print out message1
                la $a0 message1
                syscall
    
                li $v0 5        #read message1 as number1
                syscall
                move $t0,$v0    # set $t0 to the content of $v0
    
                li $v0 4        #print out message2
                la $a0 message2
                syscall
    
                li $v0 5        #read message2 as number2
                syscall
    
                move $t1,$v0
                li $v0 4
                la $a0 message3
                syscall
    
                sub $a0, $t0, $t1   #   t0 = number1 t1 = number2
    
                li $v0, 1       #   print integer
                syscall         #   run