我目前正在尝试编写一个程序来打印斐波那契数列的前 50 项。 斐波那契数列 像这样。 0,1,1,2,3,5,8,13 第 N 项是前两项之和。所以在 在上面的示例中,下一项将是 21,因为它将是前两项相加 (8+13)。
我的代码目前没有显示这个,有人可以帮助我理解为什么吗?
static void Main(string[] args)
{
int[] fibonnachi = new int[50];
fibonnachi[0] = 0;
fibonnachi[1] = 1;
int fib2ago = 0;
int fib1ago = 1;
for (int counter = 2; counter < 51; counter++)
{
fibonnachi[counter] = fibonnachi[fib2ago] + fibonnachi[fib1ago];
Console.Write(fibonnachi[counter] + " ,");
fib2ago++;
fib1ago++;
}
Console.ReadLine();
}
最佳答案
也许你不想要一个在 maxInt
处中断并溢出的版本,它通过在同一个函数中计算和输出或一些使用
预先确定尺寸的数组会弄脏内存;)
所以这是一个有趣的小版本产生一个infinte序列:
public static IEnumerable<System.Numerics.BigInteger> Fibonacci()
{
System.Numerics.BigInteger current = 0, next = 1;
while (true)
{
yield return current;
next = current + next;
current = next - current; // isn't mutation ugly to read?
}
}
你可以像这样使用它:
foreach (var i in Fibonacci().Take(10))
{
Console.Write("{0} ,", i);
}
> 0 ,1 ,1 ,2 ,3 ,5 ,8 ,13 ,21 ,34 ,
注意您可能需要它为 BigInteger
引用 Sytem.Numerics
并且您可能需要考虑技巧 和 b1
, b2
有点 - 这只是因为我不想引入一个虚拟变量来记住 b2
来更新 b1
;)
无耻的广告:
当然,您可以使用递归以更具可读性的方式执行此操作:
public static IEnumerable<System.Numerics.BigInteger>
Fibonacci(System.Numerics.BigInteger current,
System.Numerics.BigInteger next)
{
yield return current;
foreach(var n in Fibonacci(next, current+next))
yield return n;
}
Beeing C# 这可能会在一段时间后破坏你的内存(我不知道编译器是如何处理递归循环的)——但这在 F# 中更自然:
let fibonacci =
let rec create current next =
seq {
yield current
yield! create next (current + next)
}
create 0I 1I
或者可能更地道
let fibonacci =
(0I, 1I)
|> Seq.unfold (fun (current, next) ->
Some (current, (next, current + next)) )
如果你想看到真正好的东西,看看这个:
关于c# - C# 中的斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26313429/