簡體   English   中英

使用升序和降序數字在Java中打印居中金字塔

[英]Printing a centered pyramid in Java with ascending and descending numbers

Link to what I want and what I have

我正在嘗試打印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();
    }       
  }
}

你的問題在於你總是以2 ^ 7開始金字塔的右側,因為你硬編碼power2 = 7 decleration和賦值。 如果您在當前行 - 1處啟動此值,則會獲得您正在尋找的行為。 碼:

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 = row - 1;
    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();
}

這部分不對。

        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));       
    }

在第2行,您得到power2 = 6,因此顯示2 ^ 6 = 64。

你應該做類似的事情

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

您正在為power2分配常量,而不是依賴於行的值。 你能試試嗎?

int power2 =第1行;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM