首页 > 解决方案 > c#中的圣诞树树干

问题描述

我正在尝试在 C# 中绘制一棵圣诞树并设法绘制了实际的树,但是我在将树干绘制在树的中间时遇到了问题。问题是树干实际上是打印在树末端的开始处,而不是直接打印在中间。

        static void Main(string[] args)
    {
        // Get's current console window size
        int origWidth = Console.WindowWidth;

        int spaces = origWidth/2;
        int widthOfTree = 1;

        Console.WriteLine("Enter the height of the desired razor tree");
        int treeHeightUserInput = 0;
        while (!int.TryParse(Console.ReadLine(), out treeHeightUserInput))
        {
            Console.WriteLine("Enter a valid number!");               
        }

        // draws tree
        for (int i = 0; i < treeHeightUserInput; i++)
        {
            // indentation
            for (int j = 0; j < spaces; j++)
            {
                Console.Write(" ");
            }
            for (int j = 0; j < widthOfTree; j++)
            {
                Console.Write("* ");
            }
            Console.WriteLine();
            widthOfTree++;
            // reduces width of next line
            spaces--;
        }

        // draws trunk
        for (int i = 0; i < treeHeightUserInput / 3; i++)
        {
            for (int j = 0; j < spaces; j++)
            {
                Console.Write(" ");
            }
            for (int j = 0; j < widthOfTree / 3; j++)
            {
                Console.Write("| ");
            }
            Console.WriteLine();
        }
    }

这就是它的外观,我不确定问题出在哪里,因为我几乎重复使用了我用来绘制树的相同代码,但只是将高度和厚度减少了 2/3。有人猜吗? 最终结果树

标签: c#.net

解决方案


所以,spaces在循环中趋向 0 draws tree,这就是让你的树叶变成三角形的原因,但是当你画树干时,你继续使用spaces画完树叶时的样子,这意味着你的树干与树叶的左边缘对齐叶子(三角形的左下角)

如果你想将你的树干从与叶子左下角相同的缩进水平偏移,你必须spaces在到达这个循环之前增加:

        // indentation
        for (int j = 0; j < spaces; j++)
        {
            Console.Write(" ");
        }

我将把它作为练习留给你spaces在运行indentation循环之前计算一个合适的值


推荐阅读