如何编写一个程序来输出Java中的三角形数字?

her*_*rbe -6 java loops

我需要帮助.我的任务是使用嵌套循环编写Java程序以打印出以下输出模式:

                   1 
                 1 2 1 
                1 2 4 2 1 
              1 2 4 8 4 2 1 
            1 2 4 8 16 8 4 2 1 
          1 2 4 8 16 32 16 8 4 2 1 
       1 2 4 8 16 32 64 32 16 8 4 2 1 
    1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 
Run Code Online (Sandbox Code Playgroud)
//pattern1
for(int outer=1;outer<=6;outer++) // outer loop controls number of rows
{
    for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
    {
        System.out.print(inner);
    }
    System.out.println(); // move the cursor from the end of the current line to the beggiing to the next line
}

//pattern 2
for(int outer =1; outer<=6 ; outer++) //outer loop controls number of rows
{
    //3-1 create spaces before numbers.
    for(int space=1; space<=6-outer; space++ ) //group controls number of spaces
    {
        System.out.print(" ");
    }

    //3-2 print out real numbers.
    for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
    {
        System.out.print(inner);
    }
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

这两个代码是背靠背的,但我不明白我是如何让数字2 4 8 16等显示出来的,并将它们背靠背.

我的代码出了什么问题?在Java中有更好的方法吗?

jeh*_*eha 10

一个带位移和静态列大小/填充的简单版本 - 可以通过Math.getExponent()动态重复空格和格式来改进%3d...

public static void f(int n) {
    for (int i = 0; i < n; i++) {
        for (int l = n - i; l > 0; l--) { // padding for symmetry
            System.out.print("    "); 
        }
        for (int j = 0; j <= i; j++) { // "left side" of pyramid
            System.out.printf("%3d ", 1 << j); 
        }
        for (int k = i - 1; k >= 0; k--) { // "right side" of pyramid
            System.out.printf("%3d ", 1 << k); 
        }
        System.out.println();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

                              1 
                          1   2   1 
                      1   2   4   2   1 
                  1   2   4   8   4   2   1 
              1   2   4   8  16   8   4   2   1 
          1   2   4   8  16  32  16   8   4   2   1 
      1   2   4   8  16  32  64  32  16   8   4   2   1 
  1   2   4   8  16  32  64 128  64  32  16   8   4   2   1 
Run Code Online (Sandbox Code Playgroud)


Mic*_*ada 5

您将使用嵌套循环和if语句来控制输出.

此代码可以帮助您进行格式化.你必须弄清楚如何添加|| 这样它就会翻转三角形,以及如何格式化你的打印语句,看起来就是这样.

int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
    for (int col = 1; col <= totalWidth; col++) {
      if (col <= totalWidth - row) {
        System.out.print(" ");
      }else {
        System.out.print("*");
      }
    }
    System.out.println();
  }
Run Code Online (Sandbox Code Playgroud)

它会输出

       *
      **
     ***
    ****
   *****
  ******
 *******
********
Run Code Online (Sandbox Code Playgroud)