-
Code 911
Hello friends here at c programming dot com. I am writing because I'm completely baffled by a question that my instructor has posed to us. He asked us to use a recursive function (outside of the main) to figure the values of fibonacci numbers.If you haven't ever heard of them they go something like this 1,1,2,3,5,8,9,17. . . . As you can see the value of each value is the sum of the last two values. Now I know the concept of recursive functions but I would have a clue on where to even begin with this problem. Any ideas
-
You could do a board search, or just look at this thread
-
close
okay this is the stuff that I came up with as far as code is concerned
Code:
#include <iostream>
int fibonacci(int a, int b, int c);
using namespace std;
int main()
{
int a, b, c;
char j='y';
while(j!='n')
{
cout<<"Enter the first number in the fibonacci sequence: "<<"\n";
cin>>a;
cout<<"Enter the second number in the fibonacci sequence: "<<"\n";
cin>>b;
cout<<"Enter what degree you'd like to go to: "<<"\n";
cin>>c;
cout<<"The fibonacci value calculated is: "<<c<<fibonacci(a,b,c)<<"\n";
cout<<"Would you like to continue Y/N"<<endl;
cin>>j;
}
return 0;
}
int fibonacci(int a, int b, int c)
{
if(c==1)
return a;
else if (c==2)
return b;
else
return fibonacci(a,b,c - 1) + fibonacci(a, b, c - 2);
}
I'm only having one issue it keeps giving me bogus output
-
Its printing out bogus numbers because you print the value c before printing fibonacci(a,b,c).
Change
Code:
cout<<"The fibonacci value calculated is: "<<c<<fibonacci(a,b,c)<<"\n";
to
Code:
cout<<"The fibonacci value calculated is: "<<fibonacci(a,b,c)<<"\n";
-
Whoa deja vu. There is another thread about this going on as we speak!