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 a开发者_StackOverflow中文版lways returns 0. It's recursive so it makes sense to me, but how do they get 8 as an expected result?
What's 0 + 0 + 0 + 0 + 0 + 0 + ... + 0?
There's your answer.
You exit condition is wrong. Read through your code and think it through for inputs 1 and 2.
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));
}
}
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.
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.
精彩评论