C++ Fibonacci Program -
can tell me why i'm getting 1 number in sequence in advance? can't seem find what's wrong! example, if type in 10, should 34, 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 1 want (0 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))); } }
it depends on how define first number.
in code, looks starts 1, there's nothing wrong output 55 10th element.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55
however, think accidentally making right, , guessing you're trying is:
#include <iostream> using namespace std; int fibonacci (int n); int main () { int n; cout<<"fibonacci number generator"<<endl; cout<<"which 1 want (0 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 0
- the sequence this:
0, 1, 1, 2, 3, 5, 7, 13, 21, 34
Comments
Post a Comment