简单的MIPS组装-返回斐波那契数 [英] Simple MIPS Assembly - Returning a Fibonacci number

查看:120
本文介绍了简单的MIPS组装-返回斐波那契数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的汇编代码,该代码接受输入N并返回第N个斐波那契数(例如,如果输入2,则应输出1,如果输入3,则应输出2).我的代码没有引发任何错误,但是输入数字后,它返回的内容很奇怪.

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.

如果输入1,则返回2685009921. 如果输入2,则返回0.01. 如果输入3,则返回0.02. 如果输入4,它将在开始时输出要求正整数的文本,然后键入3(正确答案). 如果输入5,则不输出任何内容,再次按Enter时,将给出运行时异常(无效的整数输入syscall 5). 高于5的值都会产生奇怪的错误.

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.

这几乎就像是在以输入数字作为代码运行syscall一样,这将解释为什么前四个数字输出内容(前四个syscall输出数据).

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).

您怎么看?这是代码:

.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

推荐答案

由于某种原因,您在addi $s1, $v0, 0之后放置了syscall.该指令不应该存在.

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

这篇关于简单的MIPS组装-返回斐波那契数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆