Fibonacci sequence code prints incorrect value

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.


Here's my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 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";
	else if (position == 1) // Base case
		number = fib1;
	else if (position == 2) // Base case
		number = fib2;
	else if (position > numberOfRecursions)
	{
		number = fib1 + fib2;
		FibonacciSequence NewSequence(label, position, numberOfRecursions + 1, fib2, number);
		number = NewSequence.getNumber();
	}
// value printing code
}

int FibonacciSequence::getNumber()
{
	return number;
}
Last edited on
¡puaj!


> 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
Topic archived. No new replies allowed.