不多说直接上代码:
package com.shujia.rz.day5;
/*
* 打印杨辉三角形
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
* 1 5 10 10 5 1
*/
import java.util.Scanner;
public class yangHui {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要打印的行数:");
int x = sc.nextInt();
int n = x + 1;
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = new int[i + 1];
for (int j = 0; j < i; j++) {
if (j == 0) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
}
}
for (int i = 0; i < n; i++) {
// for (int k = x - i; k >= 0; k--) { //加这段即可输出杨辉等边三角形
// System.out.print("\t");
// }
for (int j = 0; j < i; j++) {
System.out.print(arr[i][j] + "\t" + "\t");
}
System.out.println();
}
}
}
杨辉直角三角形输出效果图:
请输入要打印的行数:
10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Process finished with exit code 0
将中间注释代码取消注释运行,输出杨辉等边三角形,效果如图:
请输入要打印的行数:
10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Process finished with exit code 0