日期:2014-05-20  浏览次数:20660 次

奇怪的金字塔--光棍节打击
各位高手帮忙看看,我写了金字塔的一个小程序,打印出来的金字塔怎么是歪的呢?好郁闷啊~~
public class Class1 {
  public static void main(String[] args) {
  int k,h;
  for (k = 1; k <= 7; k++) {  
  for (h =0; h <= k-h; h++)  
  System.out.print(" ");
  for (h = 1; h <= 2 * k - 1; h++)
  System.out.print("*");
  System.out.println("");
  }
  }
}

------解决方案--------------------
Java code

public class Class1 {

    public static void main(String[] args) {
        int k, h;
        for (k = 1; k <= 7; k++) {
            for (h = 0; h <= 7 - k; h++) {
                System.out.print(" ");
            }
            for (h = 1; h <= 2 * k - 1; h++) {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}

------解决方案--------------------
参考楼上的答案,我再给你加一点难度来帮你更好的了解,
希望对你有帮助,呵呵

/*
*
* *
* *
* *
* *
* *
 *************
 
 */
public class PyramidPrint {
public static void main(String[] args) {
int k,h;
for (k = 1; k <= 7; k++) 
{
for (h =0; h <= 7-k; h++)
System.out.print(" ");
for (h = 1; h <= 2 * k - 1; h++)
{
if(k==1||k==7)
System.out.print("*");
else {
if(h==1||h==2*k-1)
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println("");
}
}
}
------解决方案--------------------
补充一下
我上面的图形没有打印出来
应该打印出
Java code



/*
       *
      * *
     *   *
    *     *
   *       *
  *         *
 *************
 
 */
public class PyramidPrint {
      public static void main(String[] args) {
      int k,h;
  for (k = 1; k <= 7; k++) 
      {   
      for (h =0; h <= 7-k; h++)   
          System.out.print(" ");
      for (h = 1; h <= 2 * k - 1; h++)
          {
          if(k==1||k==7)
              System.out.print("*");
          else {
              if(h==1||h==2*k-1)
                  System.out.print("*");
              else
                  System.out.print(" ");
          }
          }
      System.out.println("");
      }
  }
}

------解决方案--------------------
这个呢?
public void print4(){
for(int i=0;i<7;i++){
for(int a=1;a<7-i;a++){
System.out.print(" ");
}
for(int b=1;b<=i+1;b++){
System.out.print("*");
System.out.print(" ");
}
System.out.println();
}
}
------解决方案--------------------
public class Class1 {
public static void main(String[] args) {
int k,h;
for (k = 1; k <= 7; k++) {
for (h =7; h >=k; h--)
System.out.print(" ");
for (h = 1; h <= 2 * k - 1; h++)
System.out.print("*");

System.out.println("");
}
}
}