/*
* 打印出杨辉三角形(要求打印出10行如下图)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
*/
public class Test04 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入杨辉三角形的行数: ");
int num = input.nextInt();
//int row = 10; // 三角的行数
//int[][] result;
int[][] result = new int[num][num];
for (int i = 0; i < num; i++) { // 行
result[i][0] = 1;
System.out.print(result[i][0] + "\t");
for (int j = 1; j <= i; j++) { // 列
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
System.out.print(result[i][j] + "\t");
}
System.out.println();
}
}
}
/*
* 19
打印杨辉三角 (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
*/
public class Demo36 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数: ");
int n = input.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
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 j = 0; j < n - 1 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print(arr[i][k] + " ");
}
System.out.println();
}
}
}
打印出杨辉三角形
最新推荐文章于 2022-01-05 11:57:16 发布