【问题标题】:Simple MIPS Assembly - Returning a Fibonacci number简单的 MIPS 汇编 - 返回一个斐波那契数
【发布时间】:2017-03-24 23:04:01
【问题描述】:

我正在尝试创建一个简单的汇编代码,它接受输入 N 并返回第 N 个斐波那契数(例如,如果您输入 2,它应该输出 1,如果您输入 3,它应该输出 2)。我的代码没有抛出任何错误,但是在你输入一个数字后它会返回一些奇怪的东西。

如果输入 1,则返回 2685009921。 如果输入 2,则返回 0.01。 如果输入 3,则返回 0.02。 如果输入 4,它将在开头输出要求正整数的文本,然后输入 3(正确答案)。 如果你输入 5,它什么也不输出,当你再次按 enter 时,它会给出一个运行时异常(无效的整数输入 syscall 5)。 任何高于 5 的东西都会产生奇怪的错误。

它几乎就像在运行一个系统调用,输入数字作为代码,这可以解释为什么前四个数字输出东西(前四个系统调用输出数据)。

你怎么看?代码如下:

.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

【问题讨论】:

    标签: assembly mips mars-simulator


    【解决方案1】:

    由于某种原因,您在addi $s1, $v0, 0 之后放置了一个syscall。那条指令不应该在那里。

    【讨论】:

    • 感谢修复!
    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 2020-08-11
    • 2019-07-11
    • 2013-01-25
    • 2012-11-06
    • 2013-10-13
    • 2016-06-05
    相关资源
    最近更新 更多