Non-recursive Fibonacci Sequence in Assembly

梦想与她 提交于 2021-02-11 15:45:04

问题


In some homework, I have to create a Fibonacci Sequence program in Assembly. I created this code, but it doesn't seem to be working correctly and I am not sure as to why. I believe that I am doing this correctly, but EAX remains "2" every loop.

    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

回答1:


Could look like this (untested):

    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



回答2:


Your loop simplifies to this in pseudocode:

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

As you can see, eax = val + prev will evaluate to 2 once prev gets set to 1.

You should elaborate on the specification of your problem. How many integers do you want to print out? Is this what count = 15 is for? In that case you need to be decreasing count with every iteration and checking to see that it is non-zero.

As for the Fibonacci sequence, you should be doing something like this in your loop:

// 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


来源:https://stackoverflow.com/questions/9607217/non-recursive-fibonacci-sequence-in-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!