现在要进行更改,以便每个数字都是最后2个数字的总和,因此请使其每个数字都是最后3个数字的总和 并且该系列的前3个数字是0、1、2
static void PrintFibonocciNumbers(int count)
{
int[] result = GetFibonocciNumbers(count);
PrintArray(result);
}
static int[] GetFibonocciNumbers(int count)
{
int[] result = new int[count];
for (int i = 0; i< count; ++i)
{
//need a special case if i == 0...we know for 0, the number is 0...so
//also need a special case if i == 1...we know that will be 1
// so manually set the first 2 values to the numbers that we know...0 and 1
// then the rest can be calculated automaticlly
if(i <= 1)
{
result[i] = i;
}
else
{
result[i] = result[i - 3] + result[i - 1];
}
//lets run it through the debugger
}
return result;
}
static int AddInts(int a, int b)
{
int c = a + b;
return c;
}
}
}
答案 0 :(得分:2)
我实际上会使用IEnumerable来生成序列。在我看来,表达起来更容易:
public static IEnumerable<int> GetSequence()
{
//define the initial values for the iteration
int first = 0;
int second = 1;
int next = 2;
//return the first 3 items
yield return first;
yield return second;
yield return next;
//loop forever (in reality, we might overflow) you can also limit this to
//a specific n
while (true)
{
//shift the 3 values, losing the first one (we no longer need it)
(first, second, next) = (second, next, first + second + next);
//return our result and yield the thread
yield return next;
}
}
//take the first 15 values of the IEnumerable
foreach (var val in GetSequence().Take(15))
{
Console.WriteLine(val);
}