Java 请解释以下Pascal';s三角码
在为Pascal Triangle提供的代码中,如果有人能帮我澄清以下疑问,我将不胜感激Java 请解释以下Pascal';s三角码,java,arrays,static-methods,pascals-triangle,Java,Arrays,Static Methods,Pascals Triangle,在为Pascal Triangle提供的代码中,如果有人能帮我澄清以下疑问,我将不胜感激 1 public class Pascal { 2 3 static void calculatePascal (int[][] t) { 4 for (int i=0; i<t.length; i++) { 5 // the first entry in each row is 1 6 t[i][0] = 1; 7 8
1 public class Pascal {
2
3 static void calculatePascal (int[][] t) {
4 for (int i=0; i<t.length; i++) {
5 // the first entry in each row is 1
6 t[i][0] = 1;
7
8 for (int j=1; j<t[i].length-1; j++) {
9
10 t[i][j] = t[i-1][j-1] + t[i-1][j];
11 }
12 // the last entry in each row is 1
13 t[i][ t[i].length-1 ] = 1;
14 }
15 }
16
17 static void printTriangle (int[][] t) {
18 for (int i=0; i<t.length; i++) {
19 for (int j=0; j<t[i].length; j++) {
20 System.out.print( t[i][j] + " " );
21 }
22 System.out.println();
23 }
24 }
25
26 public static void main (String[] args) {
27 int lines = Integer.parseInt( args[0] );
28 int[][] triangle = new int[lines][];
29 for (int i=0; i<lines; i++) {
30 triangle[i] = new int[ i+1 ];
31 }
32 calculatePascal(triangle);
33 printTriangle(triangle);
34 }
35
36 }
1公共类帕斯卡{
2.
3静态无效计算量(int[][]t){
4表示(int i=0;i
在第28行中,您创建的一维数组仍然保留默认分配的null
值。在第30行中,您将每个null
替换为新数组,新数组的大小比其索引大一个
Java中的2D数组实际上不是矩阵。它是数组的数组,因此不需要是矩形。在您的示例中:
三角形[0]=[1]
三角形[1]=[1,1]
三角形[2]=[1,2,1]
三角形[3]=[1,3,3,1]
…
您不需要返回任何内容,因为这里您对作为引用传递的数组执行操作
@SashaSalauyou不是三角形[]一个二维数组?它包含两件事:行数和未声明的列数?请参阅我的解释答案这正是我的困惑,因为第28行是三角形[],第30行是三角形[]。这不是Pascal。new int[]
您没有声明矩形数组。您声明了一个平面数组,它将int[]
作为值,即数组数组数组。啊,我现在明白了。谢谢您提供的示例。