如何制作带有嵌套的三角形 [英] How to make a triangle with a nested for

查看:41
本文介绍了如何制作带有嵌套的三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Java 中使用嵌套的 for 循环来制作这样的三角形

I need to use a nested for loop in Java to make a triangle like this

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

这是我的代码:

 for (int i=8; i>0; i--)
  {
  for (int j=0; j<i; j++)
  {
      System.out.print('#');
    }
    System.out.println("");
}

我得到了一个三角形,但不是我想要的.相反,我的三角形看起来像这样:

I get a triangle but not the one i want. Instead, my triangle looks like this:

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

推荐答案

使用以下代码

int f=8;`
for (int i=f; i>0; i--){

    for (int k=0; k<f-i;k++){
    System.out.print(' ');
    }
    for (int j=0; j<i; j++){
    System.out.print('*');
    }
    if(i-1!=0)System.out.println("");
 }

您的代码还在三角形的末端生成了一条不必要的线,此代码负责处理该线并能够制作所需的三角形.

Your code was also producing an unnecessary line at the end of the triangle, this code takes care of that line and is capable of making the desired triangle.

我已经对其进行了测试,请参阅此处.

I have tested it, see here.

这篇关于如何制作带有嵌套的三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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