Java语言使用二维数组打印一个 10 行杨辉三角

/*使用二维数组打印一个 10 行杨辉三角.
1
1 1
1 2 1
1 3 3  1
1 4 6  4  1
1 5 10 10 5 1
......
*/ public class TestArrayYangHui { public static void main(String[] args) { int[][] Yanghui = new int[10][]; for (int i = 0; i < Yanghui.length; i++) { // 初始化数组 Yanghui[i] = new int[i + 1]; } // 显示地为数组每个元素赋值 for (int i = 0; i < Yanghui.length; i++) { for (int j = 0; j < Yanghui[i].length; j++) { // if(j == 0 || j == i) { // Yanghui[i][j] = 1; // } Yanghui[i][0]=Yanghui[i][i]=1; if(i >= 2 && j >= 1 && j < i) { Yanghui[i][j] = Yanghui[i - 1][j - 1] + Yanghui[i - 1][j]; } } } // 遍历二维数组 for (int i = 0; i < Yanghui.length; i++) { for (int j = 0; j < Yanghui[i].length; j++) { System.out.print(Yanghui[i][j] + "\t"); } System.out.println(); } } }

 输出结果如下:

 

posted @ 2020-07-05 22:30  蔡蔡的木棉花  阅读(663)  评论(0编辑  收藏  举报