static void Main(string[] args)
{
int num1 = 0;
int num2 = 1;
int sum = 1;
while (num1 <= 15000)
{
sum = num1 + num2;
num1 = num2;
num2 = sum;
Console.WriteLine(num2);
}
Console.ReadLine();
}
最佳答案
只是为了好玩,我想用一种有趣的方式使用 LINQ 扩展方法和生成器(无限序列)来做到这一点:
// A utility class that holds math utility functions.
public static class MathUtility
{
// This method returns the fibonacci sequence which is an
// infinite sequence of numbers where each result is the
// sum of the previous two results.
public static IEnumerable<int> GetFibonacciSequence()
{
int first = 0;
int second = 1;
// first and second result are always 1.
yield return first;
yield return second;
// this enumerable sequence is bounded by the caller.
while(true)
{
int current = first + second;
yield return current;
// wind up for next number if we're requesting one
first = second;
second = current;
}
}
}
这会生成一个无限(理论上)的序列(如果让它超过 int 范围,它最终会溢出)。
然后你可以调用:
foreach(var num in MathUtility.GetFibonacciSequence().TakeWhile(num => num <= 40000))
{
Console.WriteLine(num);
}