简体   繁体   中英

Simple MIPS Assembly - Returning a Fibonacci number

I'm trying to create a simple assembly code that takes an input N and returns the Nth fibonacci number (eg if you input 2, it should output 1 and if you input 3 it should output 2). My code doesn't throw any errors, but after you input a number it returns something weird.

If you input 1, it returns 2685009921. If you input 2, it returns 0.01. If you input 3, it returns 0.02. If you input 4, it'll output the text at the beginning asking for a positive integer, then type 3 (the correct answer). If you input 5, it outputs nothing, and when you press enter again, it gives a run time exception (invalid integer input syscall 5). Anything above five gives weird errors.

It's almost as if it's running a syscall with the input number as a code, which would explain why the first four numbers output things (the first four syscalls output data).

What do you think? Here's the code:

.data
  introText: .asciiz "Type a positive integer, please! \n"
  input: .word 123


.text
  # ask user for input
  li $v0, 4
  la $a0, introText
  syscall

  # read input int
  li $v0, 5
  syscall

  # store input
  addi $s1, $v0, 0
  syscall

  # main loop
  li $s2, 0 # s2 starts at 0 and will increase until it's equal to $s1, the player input
  li $s3, 0 # this will hold the most recent fib number
  li $s4, 1 # this will hold the second most recent fib number
  loop: 
    addi $s2, $s2, 1 # increment s2 for loop
    add $s5, $s3, $s4 # make the current result the sum of the last two fib numbers
    addi, $s4, $s3, 0 # make the second most recent fib number equal to the most recent fib number
    addi, $s3, $s5, 0 # make the most recent fib number equal to the current fib number
  bne $s2, $s1, loop

  # return the answer
  li $v0, 1
  addi $a0, $s5, 0
  syscall

  # end program
  li $v0, 10 
  syscall

For some reason you've placed a syscall after addi $s1, $v0, 0 . That instruction should not be there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM