Tony The Lion
Tony The Lion

Reputation: 63240

Fibonacci class always returns 0

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?

Upvotes: 0

Views: 267

Answers (5)

Skilldrick
Skilldrick

Reputation: 70859

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

There's your answer.

Upvotes: 6

Unsliced
Unsliced

Reputation: 10552

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.

Upvotes: 0

Blindy
Blindy

Reputation: 67396

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));
    }
}

Upvotes: 2

user85509
user85509

Reputation: 37652

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.

Upvotes: 1

Oded
Oded

Reputation: 499112

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

Upvotes: 4

Related Questions