0

I am attempting to do write a simple program where I take user input two times, and then I print the result of substracting both numbers.

Currently I have detected the following issues with my code (that I am not able to solve):

  1. It seems like my code can not actually load the variables into the specify memory t1 or t2.
  2. Once my code executes it displays a huge number, not even close to the operation I am attempting to perform.
.data

x:  .word 0 # Allocate size for variables
y:  .word 0 # Allocate size for variables
x1: .word 0 # Allocate size for variables

prompt1: .asciiz    "First number: "
prompt2: .asciiz    "Second number: "
prompt3: .asciiz    "Result: "

.text

# Write first prompt
    la  $a0,prompt1
    li  $v0,4
    syscall

# ReadIn (x1);
    li  $v0,5        #Prepare to read integer
    syscall
    sw  $v0,x1      # store v0 into x1
    
# Write second prompt
    la  $a0,prompt2
    li  $v0,4
    syscall

# ReadIn (x):
    li  $v0, 5      #Prepare to read integer
    syscall
    sw  $v0, x      # Save integer from v0 into X

# Load variables into temporary address 
    lw $t2, x
    lw $t1, x1

# Perform operation
    
    sub $t0, $t2, $t1   # t0 = x-x1
    #sw $t0, y      # Save into y       
    move $a0, $t0       # Alternative Save value directly into a0
    
    # lw $a0, y     # Load value from y into a0
    li   $v0, 1             # Print Integer service
    syscall                 # Display result 
# Exit
    li  $v0,10
    syscall

mop
  • 73
  • 1
  • 9
  • 1
    `x: .word` with an empty list of words reserves space for 0 words. Perhaps you meant `.word 0` to emit 4 bytes of zeros into the output there? Use the debugger to single-step through your code and see values in registers and memory; MARS and SPIM both have debuggers built-in. – Peter Cordes Jan 14 '21 at 08:42
  • Thank you! It seems it was loading both variables in the same address?, now i can perform the subtraction but the result although I can see it in t0 the expected value i can't display it properly, it seems like I am printing the address instead of the actual value. – mop Jan 14 '21 at 08:52
  • 1
    Yes, all 3 labels had the same address. `.word` with no operands takes zero space. I didn't read most of your code since the question in your text was about how to load and store, and the duplicate answered it. Now your code doesn't match the behaviour described in the text of your question, so it's not a good SO question. Use a debugger to single-step your updated code and look at register values. Specifically, what's in `$a0` when you invoke `v0=1 / syscall` (print integer)? It's probably still the address of `prompt`, not the number you want to print. – Peter Cordes Jan 14 '21 at 08:57
  • 1
    `sw $t0,($a0)` stores to memory, not modifying the contents of the $a0 register. There's another duplicate for this: [Reading and printing an integer in mips](https://stackoverflow.com/q/19748054) – Peter Cordes Jan 14 '21 at 08:59

0 Answers0