Reputation: 984
I am unsure what the fault in my logic is. Sample output:
How many terms of the Fibonacci Sequence do you wish to compute?
1
1
1
--How many terms of the Fibonacci Sequence do you wish to compute?
5
5
5
5
5
5
5
Why is it doing this?
// Recursive Fibonacci Sequence
#include <iostream>
using namespace std;
double fib(double number);
int main(void) {
double number;
cout << "How many terms of the Fibonacci Sequence do you wish to compute?" << endl;
cin >> number;
for(int i = 0; i <= number; ++i)
cout << fib(number) << endl;
} // end main
// function fib definition
double fib(double number) {
if((number == 0) || (number == 1))
return number;
else
return fib(number - 1) + fib(number - 2);
} // end function fib
Upvotes: 1
Views: 349
Reputation: 5341
Make it:
for(int i = 0; i <= number; ++i)
cout << fib(i) << endl;
Upvotes: 1
Reputation: 17
You should just pass 'i' as the parameter in your for loop not 'number'
Upvotes: 1
Reputation: 1503379
Look at your loop:
for(int i = 0; i <= number; ++i)
cout << fib(number) << endl;
Notice how the body of the loop doesn't use i
... it always calls fib(number)
. Changing that to fib(i)
will fix it.
(It's not terribly efficient, in that you'll end up recalculating values each time, but that's a separate matter. While you could put the printing in fib
, that mixes the concerns of "what to do with the results" and "computing the Fibonacci sequence".)
Upvotes: 9