我目前正在打破这个简单的循环任务,我必须做的循环.
基本上我想要实现的是:
1)用户给出了星形金字塔的长度
2)用for循环制作金字塔.
它需要看起来像这样:(如果它需要5层高;第一行是5个空格1星;第二行4个空格2星等等.
*
**
***
****
Run Code Online (Sandbox Code Playgroud)
(难以格式化,但你得到了我的意图.)
我现在有这个
public void Pyramid()
{
Console.WriteLine("Give the hight of the pyramid");
_aantal = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= _aantal; i++) // loop for hight
{
for (int d = _aantal; d > 0; d--) // loop for spaces
{
Console.Write(_spatie);
}
for (int e = 0; e < i; e++) // loop for stars
{
Console.Write(_ster);
}
Console.WriteLine();
}
}
Run Code Online (Sandbox Code Playgroud)
输出始终是插入的空格数量,并且不会正确递减.虽然如果我调试它,它会正确倒计时.
谢谢你的回复.
您可以使用字符串类的构造函数为您创建重复,然后一次打印两个值,然后您不需要额外的for循环
static void Main(string[] args)
{
int rowHeight = 5;
for (int row = 1; row <= rowHeight; row++)
{
string spaces = new string(' ', rowHeight - row);
string stars = new string('*', row);
Console.WriteLine("{0}{1}", spaces, stars);
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
对于语义,我将使用2 for循环显示它
static void Main(string[] args)
{
int rowHeight = 5;
for (int row = 1; row <= rowHeight; row++)
{
int totalSpaces = rowHeight - row;
for (int j = 0; j < totalSpaces; j++)
{
Console.Write(" ");
}
for (int j = 0; j < row; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)