开发者

How I do fibonaci sequence under 1000? [closed]

开发者 https://www.devze.com 2022-12-19 02:57 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.
#include <iostre开发者_高级运维am>
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?? :(


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.


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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消