我正在尝试创建一个简单的汇编代码,它接受输入 N 并返回第 N 个斐波那契数(例如,如果您输入 2,它应该输出 1,如果您输入 3,它应该输出 2)。我的代码不会抛出任何错误,但是在输入数字后它会返回一些奇怪的东西。
如果输入 1,则返回 2685009921。
如果输入 2,则返回 0.01。
如果输入 3,则返回 0.02。
如果您输入 4,它将在开头输出要求正整数的文本,然后输入 3(正确答案)。
如果输入 5,它不会输出任何内容,并且当您再次按 Enter 时,它会给出运行时异常(无效的整数输入系统调用 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