首页 > 解决方案 > IA32 汇编实现中的递归斐波那契

问题描述

我目前有以下代码用于递归计算汇编中斐波那契数列的第 n 项,但是它不能正常工作(仅适用于前 3 项)。任何人都可以提供任何见解吗?

pushl %ebp 
movl %esp,%ebp
movl 8(%ebp),%eax        #retrieve argument passed to function in eax
cmpl $1,%eax             #identify if its base case     
jle fin  
decl %eax               
pushl %eax               #push n-1 to stack for next function call
call _fibonacci         
movl %eax,%ecx           #store fib(n-1) in ecx
movl 8(%ebp),%eax        
subl $2,%eax
pushl %eax              #push n-2 to stack for next function call
call _fibonacci
addl %ecx,%eax          #add fib(n-2)+fib(n-1)
fin:                    #end label
movl %ebp,%esp
popl %ebp
ret

标签: recursionassemblyx86

解决方案


call _fibonacci
addl %ecx,%eax          #add fib(n-2)+fib(n-1)

您的_fibonacci函数使用%ecx而不保存它(在非基本情况下),因此递归调用会覆盖%ecx.

您应该将第一次调用的返回值保存在_fibonacci堆栈而不是寄存器中。


推荐阅读