c# - 打印斐波那契数达 15,000 C#

标签 c# loops fibonacci

<分区>

我见过类似的问题(但在 C 中)-- Calculating Fibonacci Numbers Recursively in C关于我的问题。

我对如何在我的控制台应用程序中的 C# 中继续打印斐波那契数直到它达到大约 40,000 有点困惑,我该如何实现这一点?

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

0
1
1
2
3
5
8

and so on.

谢谢。 我不想这么说,但我灵机一动,解决了它!

这是我做的:

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);
}

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

关于c# - 打印斐波那契数达 15,000 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8333343/

相关文章:

c# - XSLT 与 XMLDocument 数据类型 -> 使用 foreach 循环遍历节点 -> 附加到文字控件

c# - excel xlsx文件解析——使用koogra

excel - 用户窗体以看似相反的顺序循环

r - 如何使用 **for** 循环清理大型数据集

c# - AvalonDock 是否可以以编程方式将 DockableContent 状态更改为 float ?

c# - 为可用于 C# 回调的 C++ dll 函数创建包装器

python - 在字典列表中查找键值,然后替换其他值

java - 斐波那契数列中 f(93) 处的数字为负值,怎么办?

java - 斐波那契数列 - 递归求和

java - 大斐波那契数的最后一位快速算法