使用 for 循环创建三角形 [英] Creating a triangle with for loops

查看:44
本文介绍了使用 for 循环创建三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法找到答案-

我需要使用 for 循环绘制一个简单的三角形.

<代码> *************************

我可以制作一个半三角形,但我不知道如何添加到我当前的循环中以形成一个完整的三角形.

<预><代码>***************

for (int i = 0; i <6; i++) {for (int j = 0; j 

解决方案

首先,您需要确保生成正确数量的 * 符号.我们需要产生 1, 3, 5 等等,而不是 1, 2, 3.这可以通过修改计数器变量来解决:

for (int i=1; i<10; i += 2){for (int j=0; j

如您所见,这导致 i1 开始,并在每一步增加 2,只要它小于10(即13579).这为我们提供了正确数量的 * 符号.然后我们需要修复每行的缩进级别.这可以按如下方式完成:

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

在打印 * 符号之前,我们打印一些空格,空格的数量取决于我们所在的行.这就是带有 k 变量的 for 循环的用途.我们可以看到 k 迭代值 4, 3, 2, 1> 和 0ì1,3, 5, 79.这就是我们想要的,因为我们在三角形中越高,我们需要放置的空间就越多.我们沿着三角形走得越远,我们需要的空间就越少,三角形的最后一行甚至根本不需要空间.

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.

*
**
***
****
*****

for (int i = 0; i < 6; i++) {
    for (int j = 0; j < i; j++) {
        System.out.print("*");
    }
    System.out.println("");
}

解决方案

First of all, you need to make sure you're producing the correct number of * 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("");
}

As you can see, this causes 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("");
}

Before printing the * 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.

这篇关于使用 for 循环创建三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆