话不多说直接上代码:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int n = sc.nextInt();
int[][] arrays = new int[n][];
for (int i = 0; i < arrays.length; i++) {
arrays[i] = new int[i + 1];
//左边打印空格,打印等腰三角形
for(int k = 0; k<= n-i; k++ ){
System.out.print(" ");
}
for (int j = 0; j < arrays[i].length; j++) {
if (i == 0 || j == 0 || i == j) {
arrays[i][j] = 1;
} else {
arrays[i][j] = arrays[i - 1][j] + arrays[i - 1][j - 1];
}
System.out.print(arrays[i][j] + " ");
}
System.out.println();
}
}
打印结果
请输入杨辉三角的行数:5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
网友评论