33 【程序 33 杨辉三角 】
题目:打印出杨辉三角形(要求打印出 10 行如下图)
程序分析:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
//可以看出 ,1.杨辉三角每一层的元素个数等于层数 2.每一层首尾元素的数值为1 3.每一层索引从1开始元素值=上一层对应索引值+上一层对应索引值的前一个
//即 array[i][j]=array[i-1][[j]+array[i-1][j-1];
1 public static void function01() { 2 int[][] array=new int[10][10];//先定义一个10810的数组 3 //按照三角形的走势,定义每行的空间长度 lenth 4 for (int i = 0; i < array.length; i++) { 5 //重新定义每行对应的长度 6 array[i]=new int[i+1]; 7 } 8 9 for (int i = 0; i < array.length; i++) { 10 //首尾值为1 11 array[i][0]=1; 12 array[i][i]=1; 13 //根据规律赋值 14 for (int j = 1; j < i; j++) {//索引从1开始而不是0 15 array[i][j]=array[i-1][j]+array[i-1][j-1]; 16 } 17 } 18 //打印相应形状的数组 19 20 for (int j = 0; j < array.length; j++) { 21 for (int j2 = 0; j2 < array[j].length; j2++) {//注意这里不是方形数组,而是三角形 22 23 System.out.print(array[j][j2]+" "); 24 } 25 System.out.println(); 26 } 27 28 29 30 }
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
打印出的三角形比较难看,不是等腰,需要改进