我目前正在绞尽脑汁为这个简单的任务循环,我必须做。
基本上,我想要实现的是:
1)用户给出输入星金字塔的长度。
2)用for循环构造金字塔。
它需要看起来像这样:(如果它需要5层高;第一行是5空间1星;第2行4空间2星等等)。
*
**
***
****(很难格式化,但你明白我的意图。)
我现在有这个
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();
}
}输出始终是插入的空格数,并且没有正确地减少。尽管如果我调试它,它的计数是正确的。
谢谢你的回应。
发布于 2015-01-05 14:47:15
明白了!
static void Main(string[] args)
{
Console.WriteLine("Give the hight of the pyramid");
string _spatie = " ";
string _ster = "*";
int _aantal = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= _aantal; i++) // loop for height
{
for (int d = i; d < _aantal; d++) // loop for spaces
{
Console.Write(_spatie);
}
for (int e = 1; e <= i; e++) // loop for stars
{
Console.Write(_ster);
}
Console.WriteLine();
}
Console.ReadKey();
}看看这个..!你错过了空间循环中高度循环的迭代器'i‘。
你会得到三角形:-
*
**
***
****对于对称的金字塔,你总是需要奇数的恒星。
发布于 2015-01-05 14:30:51
您可以使用string类的构造函数为您创建重复,然后一次打印两个值,然后不需要额外的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();
}更新
对于语义,我还将用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();
}发布于 2015-01-05 14:31:10
你的问题是
for (int d = _aantal; d > 0; d--) // loop for spaces你真的想
for (int d = _aantal - i ; d > 0; d--) // loop for spaces但它实际上只是反映了你现在拥有的东西,仍然没有创造出你想要的金字塔的样子。
我认为在控制台应用程序中最接近的方法是每隔一行减去一个空格:
for (int d = _aantal-i; d > 0; d-=2) // loop for spaces这将提供产出:
给金字塔的高度: 10
*
**
***
****
*****
******
*******
********
*********
**********https://stackoverflow.com/questions/27781525
复制相似问题