打印斐波那契数字达到15,000 C#

H B*_*amy 1 c# loops fibonacci

我已经看到了类似的问题(但在C中) - 在C中递归计算Fibonacci数字关于我的问题.

我有点坚持如何继续打印斐波那契数字,直到它达到大约40,000,在我的控制台应用程序的C#中,我怎样才能实现这一目标?

EG,我希望应用程序执行此操作:

0
1
1
2
3
5
8

and so on.
Run Code Online (Sandbox Code Playgroud)

谢谢.我不想这么说,但我有一个脑电波,并解决了它!

这是我做的:

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();
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*are 6

只是为了好玩,我想我会用一种有趣的方式来使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会产生一个无限的(理论上)序列(如果让它超过int的范围,它最终会溢出).

然后你可以打电话:

foreach(var num in MathUtility.GetFibonacciSequence().TakeWhile(num => num <= 40000))
{
    Console.WriteLine(num);
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以将演示文稿(输出)与数据生成分开.