【发布时间】:2016-12-13 17:59:53
【问题描述】:
我编写了汇编程序,它应该计算以下递归函数:
f(n) = f(n-1) + 2*f(n-2) - f(n-3)
对于 n = 0 和 n = 1,它返回 1,对于 n = 2,它应该返回 0。 但是对于这个值程序总是返回 0,看起来下面的条件从来没有满足过。
if0:
mov eax,1
jmp end
if1:
mov eax,1
jmp end
if2:
mov eax,0
jmp end
对于任何其他值(大于 2),我都会收到分段错误。 下面是完整的代码:
.intel_syntax noprefix
.globl main
.text
main:
mov eax, 3
push eax
call f
push eax
push offset msg
call printf
add esp, 8
mov eax, 0
ret
f:
push ebp
mov ebp,esp
add ebp,12
mov ebx,[ebp]
cmp ebx, 0
jz if0
cmp ebx, 1
jz if1
cmp ebx, 2
jz if2
lea ecx, [ebx-1]
push ecx
call f
pop ecx
push eax
lea ecx,[2*ebx-2]
push ecx
call f
pop ecx
pop eax
add eax,ecx
push eax
lea ecx, [ebx-3]
push ecx
call f
pop ecx
pop eax
sub eax,ecx
jmp end
if0:
mov eax,1
jmp end
if1:
mov eax,1
jmp end
if2:
mov eax,0
jmp end
end:
pop ebx
pop ebp
ret
msg: .asciz "Output = %d\n"
我不知道我做错了什么。 编辑:所以,我已经尝试过 ebp 并且我已经改变了 添加 ebp,8 到: 添加ebp,16。 而且,现在它适用于基本条件。在我看来,堆栈溢出有问题,但我没有看到它在哪里。
【问题讨论】:
-
你希望处理器在执行
if0: mov eax,1后做什么? -
当ebx等于0或1时,将1移到eax,eax是存放结果的寄存器。
-
再次阅读我的问题。 做什么 做什么 你 期望处理器要做一次它已经执行
if0: mov eax,1? -
对不起,我没听清我看到我的错我想停止执行程序。我看到我应该在这里添加
jmp end。 -
现在您更改了问题中的代码,它仍然失败吗?
标签: recursion assembly x86 intel-syntax