Simple MIPS Assembly - Returning a Fibonacci number

你说的曾经没有我的故事 提交于 2020-01-22 03:17:22

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/43010511/simple-mips-assembly-returning-a-fibonacci-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!