My assignment is to print the Fibonacci number at a given position to an on-screen label. I am supposed to create a class and use a constructor to do the recursion. Edit: The first two numbers in the tested sequence are 0 and 1.
My program is printing an incorrect value. For example, although the Fibonacci number at position 3 is 1, the number my program prints is 0.
// FibonacciSequence.h
class FibonacciSequence
{
public:
FibonacciSequence();
FibonacciSequence(HWND label, int position,int numberOfRecursions,int fib1,int fib2); // Prints every number in the Fibonacci sequence, from 1 to "position"
int getNumber(); // Returns the Fibonacci number at the given position.
~FibonacciSequence();
private:
int number; // Stores the Fibonacci number at the given position.
};
// FibonacciSequence.cpp
FibonacciSequence::FibonacciSequence(HWND label, int position,int numberOfRecursions,int fib1,int fib2)
{
number = 0;
if (position < 0)
throw"n<0";
elseif (position == 1) // Base case
number = fib1;
elseif (position == 2) // Base case
number = fib2;
elseif (position > numberOfRecursions)
{
number = fib1 + fib2;
FibonacciSequence NewSequence(label, position, numberOfRecursions + 1, fib2, number);
number = NewSequence.getNumber();
}
// value printing code
}
int FibonacciSequence::getNumber()
{
return number;
}
> Here's my code
you are missing the main() function and the destructor definition.
> the number my program prints is 0.
in the last step `numberOfRecursions' would be equal to `position'. All the conditions would fail and so you'll end with `number'=0.
Then you propagate that value upwards, and so all your objects end with its `number' = 0