1

我正在尝试编写一个使用多维数组创建帕斯卡三角形对象的类。现在,除了数组的正确初始化之外,我确实拥有一切(至少我是这么认为的)。我的程序如下:

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();
}
}

这个特定示例(new Pascal(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( y==0 || y==pascal[x].length-1) 应该适用,因此设置 pascal[1][0] = 1。

谢谢你的帮助!

4

1 回答 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 
于 2014-02-05T22:54:39.207 回答