2012-02-26 5 views
1

Link to what I want and what I haveI 2 ^行番号は、各列の中心数、数字は2^n個の中心ピラミッドを、印刷しようとして上昇してJavaの中心ピラミッドを印刷や数字

降順左は2 ^行#に昇順になり、右の数字は降順になります。私は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(); 
    }  
    } 
} 
+3

ような何かやるべきこと:***第***数学を解決し、きれいな印刷にのみ***その後、***仕事を。 –

+0

'power2'を' power1-1'のような別の値で初期化してみてください。 –

答えて

0

rowに依存する値ではなく、constant2をpower2に割り当てます。これを試してもらえますか?

int power2 = row-1;

+0

ありがとう、これは間違っていたものです。 – user1234055

2

問題は、power2 = 7の解読と割り当てをハードコードするので、常に2^7でピラミッドの右側を開始するという事実にあります。現在の行-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(); 
} 
1

この部分は正しくありません。

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