【问题标题】:C# - Recursive seriesC# - 递归系列
【发布时间】:2022-09-24 01:05:39
【问题描述】:

我在C# 中有一个递归问题。
我的任务是打印这个:
1 2 3 4 5 @ 10 8 6 4 2 1

我已经成功打印了这个:
1 2 3 4 5 @ 10 8 6 4 2 0
但是,我需要把 0 变成 1。

这是我的代码:

public static void Recursive(int a, int b)
        {
            if (a > b)
            {
                Console.WriteLine(\"@\");
                Console.WriteLine(a * 2 - 2);
            }
            else
            {
                Console.WriteLine(a);
                Recursive(a + 1, b);
                Console.WriteLine(a*2-2);
            }
        }
  • 您是否被赋予了具体的实施规则或只是需要产生的结果?
  • 我需要产生的结果。没有具体规则。
  • 所以唯一的限制是你需要编写一个输出结果的递归方法?
  • 是的。我只需要递归输出这个结果。

标签: c# recursion


【解决方案1】:

我有两种变体可以试验:

static void Recursive1(int level)
{
    if (level < 6)
    {
        if (level > 0)
        {
           Console.Write($"{level} ");
        }
        Recursive1(level + 1);
        if (level == 0)
        {
           Console.WriteLine("1 ");
        }
        else
        {
           Console.Write($"{2 * level} ");
        }
    }
    else if (level == 6)
    {
        Console.Write("@ ");
    }
}

static void Recursive2(int level)
{
    if (level < 6)
    {
       Console.Write("12345@"[level] + " ");
       Recursive2(level + 1);
       Console.Write($"{(level == 0 ? 1 : 2*level)} ");
    }
}

第二种变体可能不是您应该提交的。

【讨论】:

    【解决方案2】:

    目前尚不清楚您的“需要将 0 变为 1(打印时)”如何与递归相关,但应该有一些基本条件 - 我会介绍一个辅助方法,因为您似乎需要 3 次:

    static void PrintOneInstedOfZero(int v) => Console.WriteLine (v == 0 ? 1 : v);
    

    并在您的代码中的所有 2.5 个地方相应地使用它(Console.WriteLine(a*2-2); 没有明显原因重复两次,所以我将其视为 1.5 个调用):

    public static void Recursive(int a, int b)
    {
        if (a > b)
        {
            Console.WriteLine("@");
            PrintOneInstedOfZero(a * 2 - 2);
        }
        else
        {
            PrintOneInstedOfZero(a);
            Recursive(a + 1, b);
            PrintOneInstedOfZero(a * 2 - 2);
        }
    }
    

    【讨论】:

    • (您可以将“the * 2 print”从“then”和 else.statement 移到 if-else 之后。)
    【解决方案3】:

    这是我的看法。 output 供参考。

    public static void Recursive(int a, int b)
    {
        if (a > b)
        {
            Console.Write("@ ");
            Console.Write(a * 2 - 2);
        }
        else
        {
            Console.Write(a + " ");
            Recursive(a + 1, b);
            if (a > 1)
            {
                Console.Write(" ");
                Console.Write(a * 2 - 2);
            }
            else
            {
                Console.Write(" ");
                Console.Write(a);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 2020-11-09
      • 1970-01-01
      相关资源
      最近更新 更多