我正在尝试创建一个金字塔,该金字塔将一直延伸到中心。

代码产生了这个。

         1
       1 2 1
     1 2 3 2 1
   1 2 3 4 3 2 1


import java.util.Scanner;

for (i = 1; i<= lines; i++){ // sets rows (lines)

    for (j = a; j >= 1; j--){ // dead space on left
        System.out.printf(str," ");
    }

    for (k = 1; k != i; k++){ //left side numbers
        String str1 = "" + k;
        System.out.printf(str, str1);
    }

    a--;

    for (int l = k; l >=1; l--){ // right side numbers
        String  str2 = "" + l;
        System.out.printf(str, str2);
    }
}


我希望它看起来像这样。

                               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

最佳答案

kl应该用作指数,而不是要打印的数字。

int lines = 8;
String str = "%4s"; //pads each number to 4 spaces
for (int i = 1; i <= lines; i++)
{
    for (int j = 0; j < lines - i; j++) //Replaced a with lines - i
    {

        System.out.printf(str, " ");
    }

    for (int k = 1; k != i; k++)
    {
        //replaced k with 2 ^ (k - 1)
        String str1 = "" + (int)(Math.pow(2, k - 1));
        System.out.printf(str, str1);
    }
    for (int l = i; l >= 1; l--)
    {
        //replaced l with 2 ^ (l - 1)
        String str2 = "" + (int)(Math.pow(2, l - 1));
        System.out.printf(str, str2);
    }
    System.out.println(); //added newline between each line
}


输出:

                               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

07-24 18:58