用for循环创建一个三角形 [英] Creating a triangle with for loops
问题描述
我似乎无法找到答案 -
我需要用for循环绘制一个简单的三角形。
*
***
*****
*******
*********
我可以做一个半个三角形,但是我没有知道如何添加到我目前的循环,形成一个完整的三角形。
*
**
***
****
(int i = 0; i <6; i ++)
(int j = 0; j< i; j ++)
{
System.out.print(*);
}
System.out.println();
$ / code>
谢谢 -
pre $ $ c (int j = 0; j {
($ i = 1; i <10; i + = 2)
{
是System.out.print( *);
}
System.out.println();
code $
正如你所看到的,这导致 在打印 I don't seem to be able to find the answer to this- I need to draw a simple triangle using for loops. I can make a half triangle, but I don't know how to add to my current loop to form a full triangle. Thanks- First of all, you need to make sure you're producing the correct number of As you can see, this causes Before printing the 这篇关于用for循环创建一个三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! i
从
1
开始,并在每一步增加 2
,只要它小于 10
(即 1
, 3
, 5
, 7
, 9
)。这给了我们正确数量的 *
符号。然后,我们需要修复每行的缩进级别。这可以如下完成:
$ p $ for(int i = 1; i <10; i + = 2)$ b $ (int k = 0; k <(4-i / 2); k ++)
{
System.out.print();
for(int j = 0; j {
System.out.print(*);
}
System.out.println();
$ b *
符号我们打印一些空格,并且空格的数量根据我们所在的行而不同。这就是 k
变量的for循环的用途。我们可以看到 k
迭代了 4
, 3
, 2
, 1
和 0
when
,
5
1
, / code>,
7
和 9
。这是我们想要的,因为我们三角形的高度越高,我们需要放置的空间就越多。我们越离开三角形,我们需要的空间就越少,三角形的最后一行根本就不需要空格。 *
***
*****
*******
*********
*
**
***
****
*****
for (int i=0; i<6; i++)
{
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
*
symbols. We need to produce 1, 3, 5 et cetera instead of 1, 2, 3. This can be fixed by modifying the counter variables:for (int i=1; i<10; i += 2)
{
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
i
to start at 1
and increase by 2
at each step as long is it is smaller than 10
(i.e., 1
, 3
, 5
, 7
, 9
). This gives us the correct number of *
symbols. We then need to fix the indentation level per line. This can be done as follows:for (int i=1; i<10; i += 2)
{
for (int k=0; k < (4 - i / 2); k++)
{
System.out.print(" ");
}
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
*
symbols we print some spaces and the number of spaces varies depending on the line that we are on. That is what the for loop with the k
variable is for. We can see that k
iterates over the values 4
, 3
, 2
, 1
and 0
when ì
is 1
,3
, 5
, 7
and 9
. This is what we want because the higher in the triangle we are, the more spaces we need to place. The further we get down the triangle, we less spaces we need and the last line of the triangle does not even need spaces at all.