汇编怎么用递归求斐波那契数列啊
救救孩子吧
已经几天了还是对堆栈不够理解
大佬最好别调用库做,萌新看不懂,
比如 输入个4
那么输出是 1 1 2 3 这四项
用turbo c写了一个
#include <stdio.h>
int foo(int n)
{
if (n <= 2) return 1;
return foo(n - 1) + foo(n - 2);
}
main()
{
int i;
for (i = 1; i < 10; i++)
printf("%d ", foo(i));
return 0;
}
得到如下汇编(帮你注释了下)
ifndef ??version
?debug macro
endm
endif
?debug S "..\project\app1.c"
_TEXT segment byte public 'CODE'
DGROUP group _DATA,_BSS
assume cs:_TEXT,ds:DGROUP,ss:DGROUP
_TEXT ends
_DATA segment word public 'DATA'
d@ label byte
d@w label word
_DATA ends
_BSS segment word public 'BSS'
b@ label byte
b@w label word
?debug C E9440EAA50112E2E5C70726F6A6563745C617070312E63
?debug C E9A460A840122E2E5C696E636C7564655C737464696F2E68
?debug C E9A460A840132E2E5C696E636C7564655C7374646172672E68
_BSS ends
_TEXT segment byte public 'CODE'
; ?debug L 2
_foo proc near ;foo函数
push bp
mov bp,sp
push si
mov si,word ptr [bp+4] ;n参数放入si
; ?debug L 4
cmp si,2 ;判断n和2的大小
jg @2 ;大于2跳转到后面
mov ax,1 ;n<2则返回1
jmp short @1
@2:
; ?debug L 5
mov ax,si
dec ax ;这里就是计算n-1
push ax
call near ptr _foo ;递归调用foo
pop cx
push ax
mov ax,si
add ax,-2 ;这里是计算n-2
push ax ;结果放在堆栈上
call near ptr _foo ;递归调用foo
pop cx
mov dx,ax ;foo(n-2)的结果放在dx
pop ax ;从堆栈上得到 foo(n-1)的结果
add ax,dx //相加放在ax上作为返回值
jmp short @1
@1: ;这里是函数返回部分
; ?debug L 6
pop si
pop bp
ret
_foo endp
_TEXT ends
_DATA segment word public 'DATA'
_DATA ends
_TEXT segment byte public 'CODE'
; ?debug L 7
_main proc near
push si
; ?debug L 10
mov si,1 ;si保存的是循环变量i,这里是i=1
jmp short @7
@6: ;循环开始
; ?debug L 11
push si ;将i作为参数放入堆栈
call near ptr _foo ;调用foo(i)
pop cx
push ax ;把结果放入堆栈
mov ax,offset DGROUP:s@ ;把"%d "放入堆栈
push ax
call near ptr _printf ;调用printf
pop cx
pop cx
@5:
inc si ;i++
@7:
cmp si,10 ;i == 10?
jl @6 ;小于10返回循环开始处(6)
@4:
; ?debug L 12
xor ax,ax
jmp short @3
@3:
; ?debug L 13
pop si
ret
_main endp
_TEXT ends
?debug C E9
_DATA segment word public 'DATA'
s@ label byte
db 37 ;%
db 100 ;d
db 32 ;空格
db 0
_DATA ends
_TEXT segment byte public 'CODE'
extrn _printf:near ;外部函数printf
_TEXT ends
public _main
public _foo
end
你可以用tasm汇编得到exe
运行
大佬我采纳后总是404页面