正三角图形数列的打印

这篇博客介绍如何使用Java编程实现正三角形数列的打印,通过一个`Demo1`类展示代码细节,包括两个for循环结构,内含嵌套条件判断,根据数学计算确定数字间的空格数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习双重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();
  }
 }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值