在一些家庭作业中,我必须在Assembly中创建一个Fibonacci序列程序。我创建了这个代码,但它似乎不能正常工作,我不确定为什么。我相信我这样做是正确的,但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
可能看起来像这样(未经测试):
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
您的循环在伪代码中简化为:
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。
你应该详细说明你的问题。你想打印出多少个整数?这就是计数=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