C++ Fibonacci Program

时间:2016-02-03 03:24:35

标签: c++ fibonacci

Can anyone tell me why I'm getting one number in the sequence in advance? I can't seem to find what's wrong! For example, If you type in 10, you should get 34, but get 55 (one number ahead, i.e 11)

#include <iostream>
using namespace std;

int fibonacci (int n);

int main ()
{
    int n;
    cout << "Fibonacci number generator" << endl;
    cout << "Which one do you want (0 to exist)?";
    cin >> n;
    cout << fibonacci(n);
}


int fibonacci (int n)
{
    if (n == 0)
    {
        return 0;
    }
    else if (n == 1)
    {
        return 1;
    }
    else
    {
        return (fibonacci(n - 2) + (fibonacci(n - 1)));
    }
}

2 个答案:

答案 0 :(得分:1)

It depends on how you define your first number.

In your code, it looks like it starts from 1, so there's nothing wrong to output 55 for the 10th element.

1, 1, 2, 3, 5, 8, 13, 21, 34, 55

However, I think you were accidentally making it right, and I am guessing that what you're trying to do is:

#include <iostream>
using namespace std;
int fibonacci (int n);

int main () {
    int n;
    cout<<"Fibonacci number generator"<<endl;
    cout<<"Which one do you want (0 to exist)?";

    cin>>n;
    if(n == 0) {
        return 0;
    }
    cout<<fibonacci(n);

    return 0;
}

int fibonacci (int n) {
    if (n == 1){
        return 0;
    } else if (n == 2) {
        return 1;
    } else {
        return (fibonacci(n-2)+(fibonacci(n-1)));
    }
}

That is,

  • exit when input is 0
  • the sequence is like this: 0, 1, 1, 2, 3, 5, 7, 13, 21, 34

答案 1 :(得分:0)

The Fibonacci number sequence used to be:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55

but in modern times it has morphed to:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

See https://en.wikipedia.org/wiki/Fibonacci_number.

If you use the first sequence, the seeds are defined as:

F(1) = 1
F(2) = 1

If you use the second sequence, the seeds are defined as:

F(0) = 0
F(1) = 1

As long as we all agree that F(10) is 55, it does not matter whether it's the 10-th number in the (first) sequence or the 11-th number in the (second) sequence.