C# 使用嵌套for循环绘制ASCII树
我正在练习我的编程技巧,解决一个相当常见的问题,绘制一个由字母(比如x)组成的ASCII树来绘制树 即: 我的解决方案目前正在按我的要求运行。我只缺少一个特性(这是我问题的一部分)问题是,我不理解我使用的for循环条件。是的,我确实从另一个人那里得到了帮助,我仍然不理解他们的逻辑,但这是可行的。请,请,请向我解释for循环条件是如何为我画出我想要的东西的。x、 x 此外,我无法绘制树的最后一个“树桩”,即最后一行的最后一个x。 这是我的密码C# 使用嵌套for循环绘制ASCII树,c#,loops,for-loop,C#,Loops,For Loop,我正在练习我的编程技巧,解决一个相当常见的问题,绘制一个由字母(比如x)组成的ASCII树来绘制树 即: 我的解决方案目前正在按我的要求运行。我只缺少一个特性(这是我问题的一部分)问题是,我不理解我使用的for循环条件。是的,我确实从另一个人那里得到了帮助,我仍然不理解他们的逻辑,但这是可行的。请,请,请向我解释for循环条件是如何为我画出我想要的东西的。x、 x 此外,我无法绘制树的最后一个“树桩”,即最后一行的最后一个x。 这是我的密码 static void Main(string[] a
static void Main(string[] args)
{
int lines = 0;
Console.WriteLine("Enter number of lines: ");
string LinesAsString = Console.ReadLine();
lines = Convert.ToInt32(LinesAsString);
print(lines);
}
public static void print(int lines)
{
for (int i = 0; i < lines; i++)
{
for (int a = 0; a < lines-i-1; a++)
{
Console.Write(" ");
}
for (int y = 0; y < i*2 + 1; y++)
{
Console.Write("x");
}
Console.WriteLine();
}
}
static void Main(字符串[]args)
{
int行=0;
Console.WriteLine(“输入行数:”);
字符串LinesAsString=Console.ReadLine();
lines=Convert.ToInt32(linesastring);
打印(行);
}
公共静态无效打印(整数行)
{
对于(int i=0;i
感谢您的帮助
谢谢。很简单:
第一个for循环的每次迭代都会画一条线。假设你有4行(我不考虑带x的那一行):
第1行(i=0):3个空格1 x第2行(i=1):2个空格3 x
第3行(i=2):1个空格5x
第4行(i=3):0个空格7 x
从中,您可以获得空间数、x、行索引i和行数之间的关系
spaces = (lines - i) - 1 // decreases by one every iteration starting at lines - 1
x = i * 2 + 1 // the odd numbers in increasing order
第一个循环用于绘制空格,第二个循环用于x的第一个循环用于打印左侧填充(所有空格)。表达式
lines-i-1
来自这样一个事实:您需要将树居中,并且您知道行0
有一个x
,行1
有3个(xxx
),行2
有5个(xxxxx
)等等。但左空格的数量取决于树的总行数,因此需要考虑行
,以及当前行的索引(即变量i
的值)。要了解这两者之间的关系,您可以尝试使用少量级别,例如3:
__x 2 for the 1st line.
_xxx 1 for the 2nd line.
xxxxx 0 for the 3rd line.
第二个for
循环打印x
s。它知道第一行(i=0
)需要打印一个x
,因此当i
为0
时,y
需要为1
,因此+1
。*2
来自级数i*2+1={1,3,5,7…}
,它是每行中x
s的数量
要打印最后一个存根字符,您可以使用与第一个for
循环相同的逻辑,在第一行插入空格数,后跟一个x
Console.Write(new String(' ', lines - 1) + "x");
这应该在包含另外两个循环的for
循环之后添加。int count=0;
int count = 0;
for (int i = 0; i < 8; i++)
{
for (int x = 0; x < 8-i-1; x++)
{
Console.Write(" ");
}
for (int j = 0; j < i*2+1; j++)
{
Console.Write("X");
}
Console.WriteLine();
}
//solution to your stump problem
for (int i = 0; i < 4; i++)//the no. 4 means that you stump will be made from four X's
{
for (int x = 0; x < 8-count-1; x++)
{
Console.Write(" ");
}
Console.Write("X");
Console.WriteLine();
}
Console.ReadKey();
对于(int i=0;i<8;i++)
{
对于(int x=0;x<8-i-1;x++)
{
控制台。写(“”);
}
对于(int j=0;j
Dumb question-当您指的是“当前行的索引”时,我代表什么?我指的是变量i
,它指示在包含其他两行的的的每次迭代中,哪一行被打印到输出中。刚刚编辑了答案以澄清这一点。谢谢-这非常有帮助。我现在似乎明白了。我唯一担心的是,将来,如果遇到类似的问题,我可能需要帮助来解决这类问题!这类问题解决策略有什么建议吗P
int count = 0;
for (int i = 0; i < 8; i++)
{
for (int x = 0; x < 8-i-1; x++)
{
Console.Write(" ");
}
for (int j = 0; j < i*2+1; j++)
{
Console.Write("X");
}
Console.WriteLine();
}
//solution to your stump problem
for (int i = 0; i < 4; i++)//the no. 4 means that you stump will be made from four X's
{
for (int x = 0; x < 8-count-1; x++)
{
Console.Write(" ");
}
Console.Write("X");
Console.WriteLine();
}
Console.ReadKey();