1 public class Test413__________________ {
 2     public static void main(String[] args) {
 3         int rows = 10;
 4         for (int i = 0; i < rows; i++) {
 5             int number = 1;
 6             // 打印空格字符串
 7             System.out.format("%" + (rows - i) * 2 + "s", "");
 8             for (int j = 0; j <= i; j++) {
 9                 System.out.format("%4d", number);
10                 number = number * (i - j) / (j + 1);
11             }
12             System.out.println();
13         }
14     }
15 }

上面使用了格式化输出,看不懂看下面的。

 1 public class Test413_19 {
 2     public static void main(String[] args) {
 3         Scanner input = new Scanner(System.in);
 4         System.out.println("请输入杨辉三角的行数");
 5         int n = input.nextInt();
 6         yhs(n);
 7         input.close();
 8     }
 9     public static void yhs(int n) {
10         int h;
11         for (int i = 0; i < n; i++) {
12             h = 1;
13             for (int k = i; k < n - 1; k++) {
14                 System.out.print("  ");
15             }
16             for (int j = 0; j <= i; j++) {
17                 System.out.format("%4d", h);
18                 h = h * (i - j) / (j + 1);
19             }
20             System.out.println();
21         }
22     }
23 }
 System.out.format("%4d", h);
  这个是为了让数字之间对齐。
  这两个代码都是用的同一种算法,只是输出方式不同。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。