public class TestDemo01 { public static void main(String[] args) { //打印杨辉三角形 Scanner scanner = new Scanner(System.in); System.out.println("请输入需要打印的行数"); int n = scanner.nextInt(); int[][] arr = getTri(n); printTri(arr); scanner.close(); } private static int[][] getTri(int n) { int[][] arr = new int[n][n]; for (int i = 0; i < n; i++){ arr[i][0] = arr[i][i] = 1; } for (int i = 2; i < arr.length; i++){ for (int j = 1; j < i; j++){ arr[i][j] = arr[i-1][j-1] + arr[i-1][j]; } } return arr; } public static void printTri(int[][] arr){ for (int i = 0; i < arr.length; i++){ for (int j = 0; j <= arr.length-1-i; j++){ System.out.print(" "); } for (int j = 0; j <= i; j++){ System.out.print(" "); System.out.print(arr[i][j]); } System.out.println(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)