Incorrect output to Fibonacci series in MASM

I've been working on this code for an assignment, can't seem to get the output right. Can anyone please help me out?

NOTE: The program is compiled in MASM

  • I'm only allowed to use reg-mem and reg-reg architecture commands.
  • Only use MOV , ADD , DEC , JMP , or Jcc instructions.
  • Only use the four main registers , ie, EAX , EBX , ECX , and EDX , along with ESI register and their sub registers for arithmetical/logical operation.
  • Other then the string memory variables no other memory variable is allowed.
  • Following is the code:

    INCLUDE Irvine32.inc
    .data
    
    string1 byte "Enter number to generate Fibonacci series: ",0
    string2 byte "Fibonacci is ",0
    
    .code
    main PROC
    call    DumpRegs;
    mov     edx,offset string1;
    call    writestring;
    call    ReadInt;
    mov     ecx,eax;
    mov     eax,1;
    call    DumpRegs;
    dec     ecx;
    mov     esi,eax;
    JMP     Jumpzero;
    mov edx, offset string2;    
    call writeint           ;   Display the contents of eax register on the output device
    
    Jumpzero:
    add     eax,esi;
    call    DumpRegs;
    inc     esi;
    dec     ecx
    jnz     Jumpzero
    exit
    MAIN ENDP   
    END main
    

    ; ...
    call ReadInt
    mov ecx,eax
    
    mov eax,1
    mov edx,eax
    call writeint    ; Assuming EDX is incremented by writeint
    _generate:
        call writeint
        add eax,edx
        mov edx,eax
    loop _generate
    ; ...
    

    Oh dear, people are teaching based on that Irvine stuff? That explains a lot.

    I think you need to think about it like this:

    you need to remember 3 numbers:

  • current number

  • previous number

  • sum of current and previous

  • then move current to previous, sum to current and continue.

    So if you set things up as ebx=current value, edx=previous value, ecx= number of values to output

    then you can use a central loop like:

    fib_loop:
        mov eax, ebx
        add eax, edx
        mov edx, ebx
        mov ebx, eax
        call writeint
        dec ecx
    jnz fib_loop
    

    NOTE: I'm taking the behavior of the 'writeint' proc from your comment that it displays eax on the output device only, and assuming it doesn't mess with any of the other registers.


    Only two numbers need to be kept track of for Fibonacci. If XCHG were allowed the logic would be:

        swap(A, B)
        A += B
    

    If not, then a temp variable is needed for the swap:

        D = B
        B = A
        A = D
        A += B
    

    The initial values for A and B depend on what you want the first output to be. For example, start with A = 1 (fib(-1)), B = -1 (fib(-2)), then the sequence 0,1,1,2,3,5, ... will be produced. Or start with A = 0 (fib(0)), B = 1 (fib(-1)), to produce the sequence 1,1,2,3,5, ...

    链接地址: http://www.djcxy.com/p/89854.html

    上一篇: 无法弄清楚这段错误

    下一篇: 在MASM中向斐波那契数列输出错误