我正在尝试打印2 ^ n的中心金字塔,其中2 ^ row#是每行的中心编号,左边的数字升至2 ^ row#,右边的数字降序。我是Java的新手,花了我很长时间才能获得这么多。但是现在我被卡住了。最后一行是唯一正确的行。我不知道怎么做,所以不是每行都打印64。谁能给我一个提示吗?

我尝试弄乱每个参数-从第一行,最后一行开始最后一个循环,更改启动功率等,但我只是想不通。

谢谢您的提示!

public static void main (String [] args){

    int row;
    for (row = 0; row <= 8; row++){ // Prints each row
        for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
            System.out.print("  ");
        }

        int power1 = 0; // Power that 2 is being raised to
        for (int i = 0; i < row; i++) { // Prints left side of the pyramid
            System.out.print(" " + (int)Math.pow(2, power1));
            power1++;
        }

        int power2 = 7;
        for (int i = 1; i < row; i++) { // Prints right side of the pyramid
            power2--;
            System.out.print(" " + (int)Math.pow(2, power2));
        }

        System.out.println();
    }
  }
}

最佳答案

您正在为power2分配常量,而不是取决于行的值。你能试试这个吗?

int power2 =第1行;

关于java - 在Java中以升序和降序打印中心金字塔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9455037/

10-11 22:33
查看更多