用C#画一顶帽子

时间:2017-03-04 17:16:08

标签: c# loops

经过一个小时的头痛,我终于想出了如何在控制台上画帽子。但是,现在我很难连接帽子的左右两部分。我假设我做了所有必要的计算,所以不必检查它们。我尝试使用嵌套循环连接它们,但我搞砸了更多。这是我到目前为止所做的事情(输入一个数字来启动程序):

int n = int.Parse(Console.ReadLine());

        //top of hat
        Console.Write(new string('.', 2 * n - 1));
        Console.Write("/|\\");
        Console.Write(new string('.', 2 * n - 1));
        Console.WriteLine();
        Console.Write(new string('.', 2 * n - 1));
        Console.Write("\\|/");
        Console.Write(new string('.', 2 * n - 1));
        Console.WriteLine();

        //middle left
        for (int i = 2 * n - 1; i >= 0; i--)
        {
             Console.Write(new string('.', i));
             Console.Write("*");
             Console.Write(new string('-', n * 2 - i - 1));
             Console.Write("*");
             Console.WriteLine();
        }

        //middle right
        for (int m = 0; m < 2 * n - 1; m++)
        {
            Console.Write(new string('-', m));
            Console.Write("*");
            Console.Write(new string('.', n * 2 - m - 2));
            Console.WriteLine();
        }

        //bottom
        Console.Write(new string('*', 4 * n + 1));
        Console.WriteLine();
        for (int p = 0; p < 2 * n; p++)
        {
            Console.Write("*");
            Console.Write(".");
        }
        Console.Write("*");
        Console.WriteLine();
        Console.Write(new string('*', 4 * n + 1));
        Console.WriteLine();

How it should look like

How it looks like

1 个答案:

答案 0 :(得分:1)

中间左侧部分和中间右侧部分应位于Console.WriteLine()之前的同一循环中,因为它们必须在同一条线上绘制。

如果你在两个连续循环中绘制它们,每个包含WriteLines的它们将被绘制在彼此之上。

在左中间循环中取3个第一个写入,反转它们的顺序并在WriteLine之前添加它们。放下右中环。完成!

此外,如果您将所有'.'(在底部除外)替换为' ',您将会更好看。另外,添加Console.Write("n = ");作为第一个语句以获取输入提示。

n = 3
     /|\
     \|/
     ***
    *-*-*
   *--*--*
  *---*---*
 *----*----*
*-----*-----*
*************
*.*.*.*.*.*.*
*************

如果为

这样的行编写函数
Console.Write(new string('.', i));

您的代码将变得更加可读:

private static void Draw(char c, int count = 1)
{
    Console.Write(new string(c, count));
}

然后

Console.Write(new string(' ', 2 * n - 1));

变得简单

Draw(' ', 2 * n - 1);

另请注意,count参数是可选的,默认值为1。因此,如果您只需要绘制一个字符,则可以编写

Draw('*');