C# 如何在C控制台应用程序中创建空心正方形(用户参数)?

C# 如何在C控制台应用程序中创建空心正方形(用户参数)?,c#,console-application,C#,Console Application,我对严肃的编程还不熟悉,有一点初级Pascal的经验。我目前正试图弄清楚如何用C语言创建一个带有用户定义参数的空心正方形。我已经设法从4个边中得到3个,但对于如何管理第四个边,我没有主意。这是我目前的代码: class Program { static void Main(string[] args) { int height; int width; int counterH = 0; int counterW2 =

我对严肃的编程还不熟悉,有一点初级Pascal的经验。我目前正试图弄清楚如何用C语言创建一个带有用户定义参数的空心正方形。我已经设法从4个边中得到3个,但对于如何管理第四个边,我没有主意。这是我目前的代码:

class Program
{
    static void Main(string[] args)
    {
        int height;
        int width;
        int counterH = 0;
        int counterW2 = 0;
        int counterW1 = 0;
        Console.WriteLine("Please input the sizes of the square!");
        Console.WriteLine("Please input the height of the square.");
        height = int.Parse(Console.ReadLine());
        Console.WriteLine("Please input the width of the square");
        width = int.Parse(Console.ReadLine());
        while (counterW1 < width)
        {
            Console.Write("--");
            counterW1++;}
        Console.WriteLine();
            while (counterH < height)
            {
                Console.WriteLine("|");
                counterH++;
            }
            while (counterW2 < width)
            {
                Console.Write("--");
                counterW2++;
            }
            Console.ReadLine();
        }
    }
如果你认为我的解决方案不好,我也很高兴你能提出一个更简单/更好/更优化的解决方案。非常感谢您抽出时间

在while counterH 在此位置使用Console.Write而不是Console.WriteLine,因为您不希望在第一个管道之后出现换行/换行

例如:

    while (counterH < height)
    {
        Console.Write("|");
        int counterW3 = 0;
        while (counterW3 < width)
        {
            Console.Write(" ");
            counterW3++;
        }
        Console.Write("|" + System.Environment.NewLine);
        counterH++;
    }

因为你不能返回,你必须在一个循环中画出正方形的左右两边;在第一个while循环上设置一个断点,并逐步遍历代码。尝试一下,并考虑如何使其适应您的代码。。。Console.WriteLineW字符串'-',20@MobyDisk我是否也使用宽度计数器的值在第二列之前添加空格/表格?@Ornstein听起来很有逻辑。试试看,这是个好办法。现在,如果您可以包括示例代码和/或解释一些更类似于为什么Console.WriteLine的内容,您的答案会更好,并且可能会获得更多的投票。@ryanyuyu这看起来像是一个学习练习或学校作业,因此发布代码可能会走得太远。解释得太详细了。@MobyDisk也许吧。我只是觉得这对新用户来说仍然是有用的信息。另外,解释Console.WriteLine和Console.Write之间的细微差别仍然很有帮助。@DanielN这很好,但是你能给我解释一下System.Environment.NewLine的确切功能吗?我试图在谷歌上找到一些东西,但大多数解释似乎都不清楚。@Ornstein The System.Environment.NewLine代表换行符,取决于您的环境。在Windows上,它实际上是\r\n。