0

在一些家庭作业中,我必须在 Assembly 中创建一个斐波那契数列程序。我创建了这段代码,但它似乎不能正常工作,我不确定为什么。我相信我这样做是正确的,但 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
4

2 回答 2

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
于 2012-03-07T22:51:34.283 回答
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。

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

至于斐波那契数列,您应该在循环中执行以下操作:

// 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
于 2012-03-07T19:07:13.843 回答