tags:

views:

173

answers:

5

I have this class:

public class Fibonacci
    {
        public static int Calculate( int x )
        {
            if (x <= 0)
            {
                return 0;
            }
            else
            {
                return Calculate(x - 1) + Calculate(x - 2);
            }

        }

Per a tutorial I'm doing if one inputs 6 one should get 8 as an expected result, but when I run it, it always returns 0. It's recursive so it makes sense to me, but how do they get 8 as an expected result?

+4  A: 

You exit condition is wrong. Read through your code and think it through for inputs 1 and 2.

Oded
+1  A: 

Either the tutorial is wrong or you copied the code incorrectly. You are correct that it what you have above will always return 0. Check your base cases.

+2  A: 

The fibonacci sequence has 2 stopping points, and they're both 1 (1,1,2,3,5,...). This works:

using System;
using System.Collections.Generic;

public class Fibonacci
{
    public static int Calculate( int x )
    {
        if (x <= 1)
            return 1;
        else
            return Calculate(x - 1) + Calculate(x - 2);
    }

    public static void Main()
    {
     Console.WriteLine(Calculate(4));
    }
}
Blindy
this still doesn't produce 8 when input is 6...
Tony
It's 0 based, so if you give it 5, it'll give back 8.
Blindy
A: 

Abductio ad absurdum - Calculate(x) never actually returns a non-zero number. 8 is the sixth Fib number, but you're never creating a non-zero value from this function. As @Blindy points out, you need a more extensive and inclusive base case.

Unsliced
+7  A: 

What's 0 + 0 + 0 + 0 + 0 + 0 + ... + 0?

There's your answer.

Skilldrick