问题描述
我的任务是写一个程序,计算斐波那契数列的前七个值.给出的公式是:
My assignment is to write a program that calculates first seven values of fibonacci number sequence. the formula given is:
Fib(1) = 1, Fib(2) = 1, Fib(n) = Fib(n-1) + Fib(n-2)
我相信这是一个函数,但是我不明白如何将其合并到代码中.我需要将值放在EAX寄存器中.我正在使用MASM,但这没有任何区别.有提示吗?
I believe that is a function but I do not understand how to incorporate it into code. I need to place the values in EAX register. I am using MASM not that makes any difference. Any hints?
推荐答案
我怀疑这是一项学术任务,所以我只打算部分回答这个问题.
I suspect that this is an academic assignment so I'm only going to partially answer the question.
斐波那契数列对非负整数的正式定义如下:
The fibonacci sequence is formally defined for non-negative integers as follows:
F(n) = n | n < 2
= F(n - 1) + F(n - 2) | n >= 2
这给出了:
n | F(n)
0 | 0
1 | 1
2 | 1
3 | 2
4 | 3
5 | 5
6 | 8
7 | 13
etc etc...
您仅需几个寄存器即可完成操作,让我们对其进行识别:
You can do it with just a few registers, let's identify them:
- R (请求的斐波那契数的编号)
- R (用于计算斐波那契数)
- R (也用于计算斐波那契数)
- R (用于保存返回值的寄存器.可以与任何其他寄存器重叠)
- R (the number of the requested fibonacci number)
- R (used to calculate fibonacci numbers)
- R (also used to calculate fibonacci numbers)
- R (the register to hold the return value. can overlap with any other register)
R 作为参数传递给函数.R 应该从0开始,R 应该从1开始.
R is passed as the argument to the function. R shall start at 0, and R shall start at 1.
这是我们得到答案的方法,按例程划分:
Here's what we do to get the answer, split up by routines:
开始
- 将R 初始化为0.
- 将R 初始化为1.
- 继续循环.
- Initialize R to 0.
- Initialize R to 1.
- Continue to Loop.
循环
- 从R 中减去2.
- 如果R 小于0,请跳至完成".
- 将R 添加到R ,并将结果存储在R 中.
- 将R 添加到R ,并将结果存储在R 中.
- 跳到循环.
- Subtract 2 from R.
- If R is less than 0, jump to Finish.
- Add R to R, storing the result in R.
- Add R to R, storing the result in R.
- Jump to Loop.
完成
- 如果 R AND 1 为假(暗示 R 是偶数)跳转到 FinishEven.
- 将R 存储为返回值.
- 返回.
- If R AND 1 is false (implying that R is even) jump to FinishEven.
- Store R as the return value.
- Return.
FinishEven
- 将R 存储为返回值.
- 返回.
通过R = 5进行跟踪:
Tracing through for R = 5:
- R = 0
- R = 1
- R = R -2//R = 3
- 测试R <0//错误
- R = R + R //R = 0 +1 = 1
- R = R + R //R = 1 + 1 = 2
- 无条件跳转到循环
- R = R -2//R = 1
- 测试R <0//错误
- R = R + R //R = 1 + 2 = 3
- R = R + R //R = 3 + 2 = 5
- 无条件跳转到循环
- R = R -2//R = -1
- 测试R <0//是
- 跳到结束
- 测试R &1//是
- R = R //5
- R = 0
- R = 1
- R = R - 2 // R = 3
- Test R < 0 // false
- R = R + R // R = 0 + 1 = 1
- R = R + R // R = 1 + 1 = 2
- Unconditional Jump to Loop
- R = R - 2 // R = 1
- Test R < 0 // false
- R = R + R // R = 1 + 2 = 3
- R = R + R // R = 3 + 2 = 5
- Unconditional Jump to Loop
- R = R - 2 // R = -1
- Test R < 0 // true
- Jump to Finish
- Test R & 1 // true
- R = R // 5
我们的表显示F(5)= 5,所以这是正确的.
Our table shows that F(5) = 5, so this is correct.
这篇关于X86斐波那契程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!