c# - 在 C# 中递归打印斐波那契字符串

标签 c# recursion fibonacci

可以在没有 while 循环的情况下完成吗?

static void Main(string[] args)
{
    Console.WriteLine("Please enter a number");
    int number = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine(" #" + Fibonacci(number));
}

public static int Fibonacci(int number)
{
    if (number <= 1)
    {
        return 1;
    }
    else
    {
        return Fibonacci(number - 2) + Fibonacci(number - 1);
    }
}

我什至无法添加 Console.WriteLine在 base case 的主体中,因为它被执行了 [number] 次;不知道如何在没有循环的情况下做到这一点......

最佳答案

static void Main(string[] args)
{
    Console.WriteLine("Please enter a number");
    int number = Convert.ToInt32(Console.ReadLine());
    Fibonacci(0, 1, 1, number);
}   

public static void Fibonacci(int a, int b, int counter, int number)
{
    Console.WriteLine(a);
    if (counter < number) Fibonacci(b, a+b, counter+1, number);
}

关于c# - 在 C# 中递归打印斐波那契字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9828762/

相关文章:

c# - 将对象中的 Json 数组发送到 API

javascript - 递归函数查找给定 id 的顶级父级

recursion - Clojure 中的递归斐波那契函数

c# - 使用 WCF 服务在 .NET 中禁用 X.509 证书验证

c# - 在 gridview 的 boundfield 中找不到值?

c# - 来自 Eric Lippert 的博客 : "don' t close over the loop variable"

java - 查找字符串中最低字母(按字母顺序)的方法

C中使用递归计算数组的累加和

string - 检查数字中的数字是否可以重新排列以形成斐波那契数

c - 为什么这里需要在函数中有 if 语句才能工作?