显示Fibonacci系列中的前24个值

时间:2011-03-22 19:37:33

标签: assembly x86 fibonacci

我如何编写一个程序,用汇编语言显示Fibonacci系列中的前24个值?

如果有人可以帮助我,我会非常感激,我对汇编中的代码感到困惑。

4 个答案:

答案 0 :(得分:1)

嗯,你这样做的方式与大多数其他语言相似,就像这样:

for loop counter = 1 to 24 do
    next_number = fibonacci(previous, previous2)
    print(next_number)
    previous2 = previous
    previous = next_number

与其他语言的明显区别包括:

  1. 在这种情况下,您的“变量”可能都在寄存器中。
  2. 您可能需要编写自己的代码才能转换并打印数字。

答案 1 :(得分:1)

我留下了两个空格,因为代码取决于它将运行的系统(你没有指定编译器和操作系统)。

我没有测试过代码,但我认为它会起作用。

    mov eax, 0         ; first number
    mov ebx, 1         ; second number
                       ; edx will contain the third number (eax + ebx )

    mov ecx, 24 - 2    ; print 24 numbers (don't count the first
                         and second because they are printed in the begining)

    mov edx, eax
    call print_number  ; print the first number

    mov edx, ebx
    call print_number  ; print the second number
fibo:
    mov edx, eax
    add edx, ebx       ; edx = eax + ebx

    call print_number

    ; now we have the third number in edx
    ; eax = 1st, ebx = 2nd, edx = 3rd
    ; to prepare eax and abx for the next iteration, shift the values to the right
    ; eax = 2nd, ebx = 3rd, edx = ?
    mov eax, ebx
    mov ebx, edx

    loop fibo

    ; TO DO: exit program

print_number:
    ; TO DO: edx contains the number, print it
    return

希望它有所帮助。

答案 2 :(得分:0)

Fibonacci系列中的数字是前面两个数字之和。为了简单起见,你可以将这些数字存储在一个数组中,前两个元素设置为1.esi和edi可以指向n-1和n-2,所以fibonacci(n)= [esi] + [edi]] right ?在伪代码中它看起来像:

fibonacci    DWORD    24 dup (?)

esi = fibonacci(0)       // those are pointers to elements!
edi = fibonacci(1)

for x = 2 to 23
    fibonacci(x) = [esi] + [edi]
    esi += 4             // if you don't like DWORDs change this
    edi += 4
end loop

你可以把ecx寄存器中的x和eax寄存器中的fibonacci(x)保存。

答案 3 :(得分:-1)

尝试这个代码它可以按照你的要求工作这个答案使用循环运行24次,然后标签循环接下来首先从ax和bx获取数据然后将它们加起来这些重复的所有函数循环完成24次。

   data segment
    org 0000h
    arr dw 17h dup(0000h)
    data ends
    code segment
    assume cs:code, ds:data
    start:  mov ax,data
        mov ds,ax
        mov cx,0018h
        lea si,arr
        inc si
        mov [si],01h
    next:   mov ax,[si-1]
        mov bx,[si]
        add ax,bx
        inc si
        mov [si],ax
        loop next
        mov ah,4ch
        int 21h
     code ends
    end start
    end