繁体   English   中英

C# - 递归系列

[英]C# - Recursive series

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

目前尚不清楚您的“需要将 0 变为 0(打印时)”如何与递归相关,但应该有一些基本条件 - 我会引入辅助方法,因为您似乎需要 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);
    }
}

我有两种变体可以试验:

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

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

你已经很接近了,而不是把 0 变成 1,你能试着想想为什么最后一个 0 被打印出来,以及你是否可以通过使用另一个 if 检查来对那个条件进行例外处理? 对于将 0 变为 1,Alexis 的解决方案非常有效。

这是我的看法。 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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM