San*_*osh 2 c# algorithm console-application
我正在尝试使用C#打印马提尼酒杯图案。模式如下:
输入= 4;
0000000
00000
000
0
|
|
|
|
=======
Run Code Online (Sandbox Code Playgroud)
输入= 5;
000000000
0000000
00000
000
0
|
|
|
|
|
=========
Run Code Online (Sandbox Code Playgroud)
我可以一直到三角形(0's)。但是,我无法获得颈部(|)和底部(=)。
我的代码如下所示:
const int height = 4;
for (int row = 0; row < height; row++)
{
//left padding
for (int col = 0; col < row; col++)
{
Console.Write(' ');
}
for (int col = 0; col < (height - row) * 2 - 1; col++)
{
Console.Write('0');
}
//right padding
for (int col = 0; col < row; col++)
{
Console.Write(' ');
}
Console.WriteLine();
}
for(int i = 1; i < height; i++)
{
Console.Write('|');
}
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
它的打印如下:
0000000
00000
000
0
|||
Run Code Online (Sandbox Code Playgroud)
有人可以帮我完成脖子和底部吗?而且我的代码是否最优?您可以自由编辑完整的代码以进行优化。
提前致谢。
编辑:为颈部和底部添加了代码:
for (int i = 1; i <= height; i++)
{
// Left padding
for (int j = 1; j < height; j++)
{
Console.Write(' ');
}
Console.WriteLine('|');
}
for (int row = 0; row < height; row++)
{
for (int col = 0; col < row; col++)
{
Console.Write('=');
}
}
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
字符串构造函数有助于避免编写过多的循环
int count = 5;
for(int i = count - 1; i >= 0; i--)
{
Console.WriteLine(new string('0', 2*i + 1).PadLeft(i+count));
}
Console.Write(new string('|', count).Replace("|","|\n".PadLeft(count+1)));
Console.WriteLine(new string('=', count* 2-1));
Run Code Online (Sandbox Code Playgroud)