How I do fibonaci sequence under 1000? [closed]

Deadly 提交于 2019-12-13 10:11:46

问题


#include <iostream>
using namespace std;
void main()
{
  int i = 0;
  while (i < 1000)
  {
      int TEMP = i * 2;
      cout << i << endl;
      TEMP = i;
      i = i +1;
      // ???
  }

  return;
}

I'm so confused?? :(


回答1:


First you should check that you understand the definition of the Fibonacci numbers.

By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.

You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables.

#include <iostream>
using namespace std;
int main()
{
    int i = 0;
    int j = 1;
    while (i < 1000)
    {
        /* Print a number. */
        cout << i << endl;

        /* Set j to the sum of i and j, and i to the old value of j. */
        int TEMP = j;
        j += i;
        i = TEMP;
    }
    return 0;
}



回答2:


The Fibonacci sequence F is F(n) = F(n - 1) + F(n - 2), F(0) = 0, F(1) = 1.

Here's some psuedo-code:

Start Counter1 at 0
Start Counter2 at 1.

For i = 0 to 1000
    New value = Counter1 + Counter2
    Print new value

    Counter2 = Counter1
    Counter1 = New Value
End For

This doesn't print out 0 or 1; it starts at F(2). You can easily fix this by just printing out 0 and 1 first. Also, this code prints the first 1000 numbers. If you change this to: While Counter1 < 1000, you'll stop when you reach or pass 1000.

It's up to you to implement it, and make sure you understand how it works.




回答3:


If you would like just a hint, Google "recursion".

If you would like the answer, Google "recursion fibonacci C++", but PLEASE try to work it out with the hint above :) It's worth it.



来源:https://stackoverflow.com/questions/2210928/how-i-do-fibonaci-sequence-under-1000

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!