如何在控制台中绘制 (c#)

how to draw in the console (c#)

最近在 IT class 我们获得了一个简单的控制台程序,它使用嵌套循环来绘制一个直角三角形。我真的不明白这段代码中发生了什么。有人可以解释它是如何工作的以及如何在控制台中创建其他形状吗?这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Task_4
{
    class nestedLoop
    {
        static void Main(string [] args)
        {
            int i, j;
            i = j = 0;
            for (i = 1; i <= 5; i++)
            {
                for (j = 1; j <= i; j++)
                {
                    Console.Write('*');
                }
                Console.Write("\n");
            }
            Console.ReadLine();
        }
    }
}

有两个for循环,每个循环都有一个变量i或j分配给它,它会增加一个,直到它达到它的上限,(i <= 5)或(j <= i)。使用这个逻辑,第一个循环 i 是 1 所以 j 只会是 1,然后我们再次循环,这次 i 是 2 所以 j 将 运行 两次,依此类推,下面是一个小例子

循环 1,i = 1 j = 1 *

循环 2,i = 2 j = 2 **

循环 3,i = 3 j = 3 ***

循环 4,i = 4 j = 4 ****

循环 5,i = 5 j = 5 *****

所以一旦我们画好了星星,我们就会得到这个。

方形

For(int i = 0; i < 5; i++)
{
   For(int j = 0; j < 5; i++)
      Console.Write("*");
}

高矩形

For(int i = 0; i < 10; i++)
{
   For(int j = 0; j < 5; i++)
      Console.Write("*");
   Console.Write("\n");
}

长方形

For(int i = 0; i < 5; i++)
{
   For(int j = 0; j < 10; i++)
      Console.Write("*");
   Console.Write("\n");
}

变量 i 的外层循环循环了 5 次。带有变量 j 的嵌套循环的每个循环都将设置与 i 循环的循环次数一样多的 '*' 并在末尾设置一个换行符。 因此,如果它是 i 的第一个循环,则 j 循环将在第二个循环 '**' 上设置 1 '*',依此类推。 这将导致以下输出:

*
**
***
****
*****

将 i 替换为行 用列替换 j 你应该能从那里弄明白

但本质上该程序可以翻译为:

0a) 在 1 上初始化 i。

0b) 在 1 上初始化 j。

1)在第I行,如果J小于或等于I,画一个星,然后给J加1。

2) 重复1)直到J大于I。

3)若J大于I,则I加1,从0b)重复,直到I = limit(5)。

旁注:更简洁的代码会像这样

using static System.Console;

namespace ExamPrep
{
    class Program
    {
        static void Main(string[] args)
        {
            const int maxHeight = 5;

            for (int height = 0; height < maxHeight; height++)
            {
                for (int width = 0; width <= height; width++)
                {
                    Write('*');
                }
                Write("\n");
            }
            ReadLine();
        }
    }
}

可能想用 'currentHeight' 替换 'height',但意图比只使用字母更清楚。