使用嵌套的for循环绘制ASCII树

时间:2014-01-16 19:42:33

标签: c# loops for-loop

我正在练习我的编程技巧,有一个相当常见的问题,就是画一个由字母组成的ASCII树(比方说是x)来画一棵树。

即:

Prompt: Enter the number of lines for your tree: 5
Output: 
   x
  xxx
 xxxxx
xxxxxxx
   x

我所拥有的解决方案目前正在按照我的意愿运作。我只缺少一个功能(这是我的问题的一部分)。 问题是,我不明白我使用的for循环条件。是的,我确实得到了另一个人的帮助,我仍然不理解他们的逻辑,但它确实有效。拜托,请向我解释for循环条件实际上是如何为我绘制我想要的东西。 x.x中 此外,我无法绘制树的最后一个“残端”,即最后一行中的最后一个。

这是我的代码。

static void Main(string[] args)
        {
            int lines = 0;
            Console.WriteLine("Enter number of lines: ");
            string LinesAsString = Console.ReadLine();
            lines = Convert.ToInt32(LinesAsString);
            print(lines);
        }


        public static void print(int lines)
        {

            for (int i = 0; i < lines; i++)
            {
                for (int a = 0; a < lines-i-1; a++)
                {
                    Console.Write(" ");
                }

                for (int y = 0; y < i*2 + 1; y++)
                {

                    Console.Write("x");


                }
                Console.WriteLine();

            }





        }

感谢任何帮助。

感谢。

3 个答案:

答案 0 :(得分:0)

这很简单:

第一个for循环的每次迭代都会绘制一条线。假设你有4行(我不考虑那个孤独的x):

第1行(i = 0):3个空格1 x
第2行(i = 1):2个空格3 x
第3行(i = 2):1个空格5 x
第4行(i = 3):0空格7 x

通过这些,您可以获得空格数,x,行索引i和行数之间的关系。

    spaces = (lines - i) - 1 // decreases by one every iteration starting at lines - 1
    x = i * 2 + 1 // the odd numbers in increasing order

第一个循环绘制空格,第二个循环绘制x的

答案 1 :(得分:0)

第一个for循环打印左边的填充(所有空格)。表达式lines - i - 1来自于您需要居中树的事实,并且您知道行0只有一个x,行1有3个xxx }),行2有5个(xxxxx),依此类推。但是左边空格的数量取决于树的总行数,因此你需要考虑lines以及当前行的索引(这是变量的值{{1 }})。要弄清楚这两者之间的关系,你可以尝试使用少量级别,让我们说3:

i

第二个__x 2 for the 1st line. _xxx 1 for the 2nd line. xxxxx 0 for the 3rd line. 循环打印for s。它知道第一行(x)需要打印一个i = 0,所以当xi时,0需要y 1}},因此1+ 1来自进度* 2,即每行中i * 2 + 1 = {1, 3, 5, 7...}的数量。

要打印最后一个存根字符,您可以使用与第一个x循环相同的逻辑,插入第一行的空格数,后跟一个for

x

这应该在包含其他两个循环的Console.Write(new String(' ', lines - 1) + "x"); 循环之后添加。

答案 2 :(得分:0)

int count = 0;
            for (int i = 0; i < 8; i++)
            {
                for (int x = 0; x < 8-i-1; x++)
                {
                    Console.Write(" ");
                }
                for (int j = 0; j < i*2+1; j++)
                {
                    Console.Write("X");
                }
                Console.WriteLine();
            }
            //solution to your stump problem
            for (int i = 0; i < 4; i++)//the no. 4 means that you stump will be made from four X's
            {
                 for (int x = 0; x < 8-count-1; x++)
                {
                    Console.Write(" ");

                }
                 Console.Write("X");
                 Console.WriteLine();
            }
            Console.ReadKey();
相关问题