问题描述
我已经用RISC-V汇编语言编写了用于计算第n个斐波那契数的代码。它有两个部分-fib.s
和runtest.s
,它们将n
的值加载到a0
中,并调用fib
,计算第n个斐波那契数(无递归) ),将结果加载到a0
本身并返回。这是我的代码:
.global fib # the runtest.s will give an a0 value as input n and call fib
fib:
li a1,0 # This is a
li a2,1 # This is b
li a3,0 # This is c
li a4,2 # This is i
li a6,2 # dummy,just to check a0 with
ble a0,a6,cond1 # check if a0 <= 2
bgt a0,head # if a0 > 2,proceed to loop
head: # start of loop
add a3,a1,a2 # Here I'm implementing the space optimized version of fibonacci series without recursion:
mv a1,a2 # for i in range(2,n+1): c = a + b; a = b; b = c; return b
mv a2,a3
addi a4,a4,1
blt a4,a0,head
bge a4,end # iterates n-1 times and goes to end
cond1:
li a0,1 # if n==1 or n==2 return 1
li a7,93
ecall
end:
mv a0,a2 # copying the value of a2 (which is b) to a0,since the testbench
li a7,93 # runtest.s is setup that way.
ecall
这是我的测试台(runtest.s
):
.global _start
_start:
# Load 'n' into a0 and call fib
# Test 1
li a0,1 # Check n'th Fib number
call fib
li a5,1 # Expected result
bne a0,a5,.FINISH
# Test 2
li a0,3
call fib
li a5,3
bne a0,.FINISH
# Test 3
li a0,7
call fib
li a5,13
bne a0,.FINISH
# Test 4
li a0,9
call fib
li a5,34
bne a0,.FINISH
# Test 5
li a0,20
call fib
li a5,6765
bne a0,.FINISH
# Test 6
li a0,30
call fib
li a5,832040
bne a0,.FINISH
# Finished tests
li a5,0 # All passed
.FINISH:
mv a0,a5
li a7,93
ecall
每次运行此代码时,我只会得到一个返回值1。有人可以指出其中的错误吗?另外,如果有更好的方法来实现相同的逻辑,也请让我知道。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)