正三角图形数列的打印

来源:互联网 发布:人工智能会毁灭人类吗 编辑:程序博客网 时间:2024/06/05 13:31
学习双重for循环,应用时候涉及特殊图形打印。下面的图形费了我几个小时才写出来,如果你是初学者,还真别小瞧它,不信自己写看看。

数字不是问题,空白区域空格也好计算,主要问题是:数字后空格,算的我头都大了,不过最终还是被我搞定了。(*^__^*)嘻嘻……。教材上也有另外一种方式,没看,想要的找我要。我写的代码如下:

public class Demo1 {
 public static int  math(int i){
  int k = 1;
  if (i == 0){
   k = 1;
  }
  else{
   for (int j = 1;j<i+1 ;j++ ){
     k =2*k;
   }
  }
  return k ;
 }
 public static void main(String[] args){
  // 特殊图形的打印正三角图形
  int n = 9;
  for (int i = 0;i<n ;i++ ){
    for (int k = 0;k<n-i-1;k++ ){
     System.out.print(" "+"   ");
    }
    for(int k = 0;k<i+1;k++ ){
     if (k != i){
     
      if (math(k+1)>100){
       System.out.print(math(k)+" ");
      }
      else if (math(k+1)>10){
       System.out.print(math(k)+"  ");
      }
      else{
       System.out.print(math(k)+"   ");
      }
     }
     else{
      if (math(k-1)>100){
       System.out.print(math(k)+" ");
      }
      else if (math(k-1)>10){
       System.out.print(math(k)+"  ");
      }
      else{
       System.out.print(math(k)+"   ");
      }
     }
    }
    for(int k = i-1;k>=0;k-- ){
     if (math(k-1)>100){
      System.out.print(math(k)+" ");
     }
     else if (math(k-1)>10){
      System.out.print(math(k)+"  ");
     }
     else{
      System.out.print(math(k)+"   ");
     }
     
    }
    for (int k = 0;k<n-i-1 ;k++ ){
     System.out.print(" "+"   ");
    }
   System.out.println();
  }
 }

}




0 0
原创粉丝点击