I'm writing this simple MIPS assembly code for a class. The idea is for the program to take three inputs: two integers followed by a basic mathematical operator (i.e. '+', '-', '*', or '/'). It performs the indicated operation on the two integers and outputs the result.
Or rather, that's what it's supposed to do. However, when you enter a '+' it gives you the difference between the two numbers and when you enter a '-' it outputs their product. Even weirder, multiplication and division work fine! Could someone better than me at assembly language help me understand what's going on here? Thank you!
.text
Main:
# Prompt for the integer to enter
li $v0, 4
la $a0, prompt1
syscall
# Read the integer and save it in $s0
li $v0, 5
syscall
move $s0, $v0
# Prompt for another integer to enter
li $v0, 4
la $a0, prompt2
syscall
# Read the integer and save it in $s1
li $v0, 5
syscall
move $s1, $v0
# Prompt for operator
Operator:
li $v0, 4
la $a0, prompt3
syscall
# Read the operator and save it in $s2
li $v0, 12
syscall
addi $s2, $zero, 0
move $s2, $v0
# Print ASCII values for debugging
li $v0, 1
move $a0, $s2
syscall
# Branch to addition
li $t0, '+'
beq $s2, $t0, Add
# Branch to subtraction
li $t0, '-'
beq $s2, $t0, Subtract
# Branch to multiplication
li $t0, '*'
beq $s2, $t0, Multiply
# Branch to division
li $t0, '/'
beq $s2, $t0, Divide
# Handle unexpected character
li $v0, 4
la $a0, error
syscall
j Operator
Add:
add $s4, $s0, $s1
j Print
Subtract:
sub $s4, $s0, $s1
j Print
Multiply:
mul $s4, $s0, $s1
j Print
Divide:
divu $s0, $s1
mflo $s4
j Print
Print:
# Line break
li $v0, 4
la $a0, br
syscall
# Print 1st value
li $v0, 1
move $a0, $s0
syscall
# Print operator
li $v0, 11
move $a0, $s2
syscall
# Print 2nd value
li $v0, 1
move $a0, $s1
syscall
# Print equals sign
li $v0, 4
la $a0, e
syscall
# Print result
li $v0, 1
move $a0, $s4
syscall
# Exit the program
Exit:
li $v0, 10
syscall
.data
prompt1: .asciiz "\nPlease enter an integer: "
prompt2: .asciiz "\nPlease enter another integer: "
prompt3: .asciiz "\nPlease choose a math operation (+, -, *, or /): "
error: .asciiz "\nNot gonna work!"
br: .asciiz "\n"
e: .asciiz "="
My best guess is that it has something to do with the way the branching logic works, but I tried having it print the operation it was doing (e.g. print "adding" when it hit the addition branch) and that seemed to work. It seems to hit the correct branches but somehow perform the wrong operations. I'm at a loss.