java 2 的倍数的金字塔不起作用

java pyramid with multiple of 2 not working

我想创建一个金字塔并将每个数字乘以二直到到达中间然后除以二,如下例所示。

然而,在编写我的代码后,我无法让数字加倍 (i*2),然后一旦它到达中心,它就会除以二,直到它变成 1

我的输出:

 package question5;

 public class Pyramid {

 public static void main(String[] args) {
    int x = 5;
    int rowCount = 1;

    System.out.println("Here Is Your Pyramid");

    //Implementing the logic

    for (int i = x; i > 0; i--)
    {
        //Printing i*2 spaces at the beginning of each row

        for (int j = 1; j <= i*2; j++)
        {
            System.out.print(" ");
        }

        //Printing j value where j value will be from 1 to rowCount

        for (int j = 1; j <= rowCount; j++)             
        {
        System.out.print(j+" ");
        }

        //Printing j value where j value will be from rowCount-1 to 1

        for (int j = rowCount-1; j >= 1; j--)
        {                    
        System.out.print(j+" ");             
        }                          

        System.out.println();

        //Incrementing the rowCount

        rowCount++;
    }
}
}

this is the weird output of it

现在您正在输出 j,一个从 15 的数字。您想输出 2j-1,这很简单:1 << (j - 1).

您还需要右调数字。您的打印语句将变为:

System.out.printf("%4d", 1 << (j - 1));

这有效...您可以使用 math.pow 方法。

public class test {

     public static void main(String[] args) {
        int x = 5;
        int rowCount = 1;

        System.out.println("Here Is Your Pyramid");
        //Implementing the logic

        for (int i = x; i > 0; i--)
        {
            //Printing i*2 spaces at the beginning of each row
            for (int j = 1; j <= i*2; j++)
            {
                System.out.print(" ");
            }

            //Printing j value where j value will be from 1 to rowCount

            for (int j = 0; j <= rowCount-1; j++)             
            {
            System.out.printf("%2d", (int)Math.pow(2, j));  
            }

            //Printing j value where j value will be from rowCount-1 to 1

            for (int j = rowCount-1; j >= 1; j--)
            {                    
            System.out.printf("%2d", (int)Math.pow(2, j-1));
            }                          

            System.out.println();

            //Incrementing the rowCount

            rowCount++;

        }
    }
    }