1

我将如何编写一个程序,以汇编语言显示斐波那契数列中的前 24 个值?

如果有人可以帮助我,我将不胜感激,我对汇编中的代码感到困惑。

4

4 回答 4

1

好吧,你的做法与大多数其他语言的做法非常相似,如下所示:

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

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

  1. 在这种情况下,您的“变量”可能都在寄存器中。
  2. 您可能必须编写自己的代码来转换和打印数字。
于 2011-03-22T20:31:55.647 回答
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

希望能帮助到你。

于 2011-03-23T16:26:15.080 回答
0

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

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

您可以将 x 保存在 ecx 寄存器中,将 fibonacci(x) 保存在 eax 寄存器中。

于 2011-03-22T20:31:09.873 回答
-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
于 2018-03-25T07:22:20.027 回答