汇编中的非递归Fibonacci序列

时间:2012-03-07 18:41:18

标签: assembly masm fibonacci irvine32 non-recursive

在一些作业中,我必须在Assembly中创建一个Fibonacci Sequence程序。我创建了这个代码,但它似乎没有正常工作,我不确定为什么。我相信我正确地做到了这一点,但EAX在每个循环中仍然是“2”。

    INCLUDE Irvine32.inc
    .data
        prev DWORD ?
        next DWORD ?
        val DWORD ?
        count DWORD ?
        total DWORD ?

        myMsg BYTE "Fibonacci Sequence ",0dh,0ah,0

   .code
    main PROC
       mov ecx,15
       mov val,1
       mov prev,-1
       mov eax,1
       mov edx,OFFSET myMsg
       call WriteString

    L1:
       mov count,ecx
       mov ebx,val
       add ebx,prev
       mov total,ebx
       mov ebx,val
       mov prev,ebx
       mov eax,total
       mov val, ebx
       call WriteInt
       call Crlf
       loop L1

    exit
    main ENDP
    END main

2 个答案:

答案 0 :(得分:2)

可能看起来像这样(未经测试):

    mov  ecx, 15
    mov  eax, 0    ;a = 0
    mov  ebx, 1    ;b = 1
_fib:
    mov  edx, eax 
    add  edx, ebx  ;sum = a + b
    mov  eax, ebx  ;a = b
    mov  ebx, edx  ;b = sum
    loop _fib

答案 1 :(得分:1)

你的循环在伪代码中简化为:

L1:
   count = ecx; // count === 15
   eax = total = val + prev; // prev = -1 => eax = 0. prev = 1 => eax = 2
   prev = val; // sets prev = 1, val doesn't change so prev = 1 after the first iteration

如您所见,一旦prev设置为1,eax = val + prev将评估为2。

您应该详细说明问题的规范。你想要打印多少个整数?这是计数= 15的用途吗?在这种情况下,您需要在每次迭代时减少计数并检查它是否为非零。

至于Fibonacci序列,你应该在你的循环中做这样的事情:

// lets say that eax is the current integer in the sequence and prev is the previous integer
// then the next integer = eax + prev
ebx = eax + prev
prev = eax
eax = ebx