1

我正在嘗試編寫一個類,該類使用多維數組創建一個pascal三角形的對象。現在我確實擁有了一切(至少我認爲是這樣),除了正確的初始化數組。我的程序讀取如下:錯誤的多維數組初始化嘗試構建pascal三角形(JAVA)

class Pascal{ 

//Object variables 
int size; 
int[][] pascal; 

Pascal(int size){ //Constructor 

    this.size = size; //Defines how many rows/columns the triangle has. 
    pascal = new int[size][]; 

    //Allocation of the arrays 
    for(int i=0;i<pascal.length;i++) 
     pascal[i] = new int[i+1]; 

    pascal[0][0] = 1; //the tip of the triangle is always one. Also you need a value to start with. 


    //Initialisation of the elements 
    for(int x=0;x<pascal.length;x++){ 
     for(int y=0;y<pascal[x].length;y++){ 

      if(x>0){ 

       if(y==0 || y == (pascal[x].length)-1) 
        pascal[x][y] = 1; //Initialisation of the first and last element of the actual array x 

       else 
        pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1];//Initialisation of all elements in between 

      } 
     } 
    } 

} 


//The print method needed to display the pascal triangle 
void print(){ 
    for(int i=0;i<pascal.length;i++){ 
     for(int k=pascal.length;k>i;k--) 
      System.out.print(" "); 
     for(int j=0;j<pascal[i].length;j++) 
      System.out.print(pascal[i][j]+" "); 
     System.out.println(); 
    } 
} 


//main function 
public static void main(String... args){ 
    Pascal p = new Pascal(5); //example triangle consisting of 5 rows total 
    p.print(); 
} 
} 

在此particiular示例中的輸出(新帕斯卡(5);)應該是:

1 
    1 1 
    1 2 1 
1 3 3 1 
1 4 6 4 1 

然而,它是:

1 
    2 1 
    1 1 1 
1 0 1 1 
1 0 0 0 1 

我知道這個問題必須在代碼的數組初始化部分的某個地方,這可能是一個簡單的錯誤,但在顯示器上主演不會讓我在任何地方了:/

以防萬一你不只是想給我答案: 從我的理解數組元素pascal [1] [0]應該是1而不是2,因爲當for循環值x是1和值y是0 if if條件if(y == 0 || y == pascal [x] .length-1)應該適用於設置pascal [1] [0] = 1.

感謝您的幫助!

回答

1

在構造函數中初始化2D數組時,在else中,您的分配不正確。要初始化當前元素,但左側是不正確的(和不符合if):

pascal[x-1][y-1] = pascal[x-1][y] + pascal[x-1][y-1]; 

嘗試[x][y]元素本身。

pascal[x][y] = pascal[x-1][y] + pascal[x-1][y-1]; 

僅製作這種變化,我得到正確的輸出:

 1 
    1 1 
    1 2 1 
    1 3 3 1 
1 4 6 4 1 
+0

我得到了相同的只是第二次。必須是在這裏的時間。感謝你及時的答覆。這個問題真的是浪費webspace -_- – user3277290