使用嵌套for循环来实现加倍和减半的金字塔

时间:2015-01-22 21:38:51

标签: java loops for-loop nested

                 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 

我需要使用嵌套for循环创建这个金字塔, 到目前为止,我所知道的是我需要三个for循环。 我知道循环是如何工作的,并且对java的基本原理有很好的把握,但我对这是如何工作没有世俗的想法。

2 个答案:

答案 0 :(得分:0)

只是在没有调试的情况下编写了这个,但它应该产生这个金字塔:

      0       
    0 1 0    
  0 1 2 1 0  
0 1 2 3 2 1 0



int pyramidHeight = 4;
for(int i = 0; i < pyramidHeight;i++){
  for(int j = 1; j < pyramidHeight*2;j++){
    if( j < pyramidHeight - i || j > pyramidHeight + i ){
      System.out.print(" ");

    }
    else{
      System.out.print(i - Math.abs(pyramidHeight - j));
    }
    System.out.print(" ");
  }
  System.out.println();
}
&#13;
&#13;
&#13;

通过两个简单的更改,您应该获得金字塔。

答案 1 :(得分:-1)

这应该有效!请注意,每行计算总共2 * i + 1个元素,其中i是您当前的行号。

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

        int lim = 5;
        int spaceLim = lim*2;

        for (int i=0; i < lim; i++){ // Number of rows is the key here (pow 2)

            String s = "%" + spaceLim + "s";
            System.out.printf(s, "");
            if (i == 0){
                System.out.print(1);
            }
            else{
            for (int j=0; j<i; j++) {
                System.out.printf("%1.0f ",(Math.pow(2.0, (double)(j))));
            }

            for (int j=i; j>=0; j--){
                System.out.printf("%1.0f ", (Math.pow(2.0, (double)(j))));
            }

            }
            System.out.println();
            spaceLim -= 2;
        }
    }
}

工作解决方案的演示在这里 - http://ideone.com/J2fcQw