繁体   English   中英

c#中的圣诞树树干

[英]Christmas Tree trunk in 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。 有人猜吗? 最终结果树

因此,在draws tree循环中, spaces趋向于 0,这就是使树叶呈三角形的原因,但是当您绘制树干时,您继续使用spaces ,就像您完成绘制树叶时所形成的一样,这意味着您的树干与叶子的左边缘(三角形的左下角)

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

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

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

当绘制树的顶部时, spaces会减少( spaces-- )。 所以它的值不符合您的需求,您必须在绘制树干的循环之前重置它或增加它(通过treeHeightUserInput/3 )。

感谢 Caius Jard,我能够在一定程度上解决这个问题。 我怀疑这是一种解决问题的干净方法,但它确实有效。

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

暂无
暂无

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

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