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.每个数等于它上方两数之和。
2.每行数字左右对称,由1开始逐渐变大。
3.第n行的数字有n项。
4.等边的杨辉三角每一行前面的空格为总行数减去一。
import java.util.Scanner;
public class TriangleArray {
public static int num(int x, int y) {//x表示行,y表示列
if (y == 1 || y == x) {
return 1;
}
int c = num(x - 1, y - 1) + num(x - 1, y);
return c;
}
public static void calculate(int row) {
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= row - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) { // 打印空格后面的字符, 从第1 列开始往后打印
System.out.print(num(i, j) + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("打印杨辉三角形的行数:");
int row = scan.nextInt();
calculate(row);
}
}
输出结果: