【问题标题】:Printing all the integers from 0 to n in in descending order order using recursive method [duplicate]使用递归方法按降序打印从0到n的所有整数[重复]
【发布时间】:2016-10-03 19:10:24
【问题描述】:

我编写了一个小程序来练习递归,但我无法让它按您所见的那样工作。在当前状态下,该程序有点工作,但不像我想要的那样。

我正在寻找的是按降序打印从 int N 到 0 的值,而不是当前在代码中的从 10 到 N 的值。

private static void DescendingRecursion(int n)
    {

        if (n == 10) // Base case
            return;
        else {
            DescendingRecursion(n + 1);
            Console.Write(n + " ");
        }
    }
    static void Main(string[] args)
    {
        DescendingRecursion(0);
    }

(输出:9 8 7 6 5 4 3 2 1 0)

【问题讨论】:

  • 递归不应该从最大值开始并返回一个字符串和当前计数-1吗?

标签: recursion


【解决方案1】:

为什么不在每个递归调用中传递最大值并传递n - 1 呢?例如

private static void DescendingRecursion(int n)
{
    if (n < 0) { // base case
        // optional: ensures a newline at the end
        Console.WriteLine();
    } else {
        Console.Write(n + " ");
        DescendingRecursion(n - 1);
    }
}
static void Main(string[] args)
{
    DescendingRecursion(5);
    // Output: 5 4 3 2 1 0
}

编辑

一种更接近原始代码的替代方法,尽管我绝对更喜欢上面的代码:

private static void DescendingRecursion(int max, int n=0)
{
    if (n <= max) {
        DescendingRecursion(max, n + 1);
        Console.Write(n + " ");

        // optional: ensures there's a newline at the end
        if (n == 0) {
            Console.WriteLine();
        }
    }
}
static void Main(string[] args)
{
    DescendingRecursion(5);
    // Output: 5 4 3 2 1 0
}

EDIT2

返回 string 而不是打印的版本:

private static string DescendingRecursion(int n)
{
    if (n < 0) {
        return "";
    }
    return n + " " + DescendingRecursion(n - 1);
}
static void Main(string[] args)
{
    Console.WriteLine(DescendingRecursion(5));
    // Output: 5 4 3 2 1 0
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2022-01-13
    相关资源
    最近更新 更多