Java 杨辉三角问题

来源:百度知道 编辑:UC知道 时间:2024/06/21 14:44:20
public class YangHui {

public static void main(String[] args){
int [][] a = new int[12] [12];
for(int i=1;i<=11;i++){
a[i][0]=1;
a[i][i]=1;
for(int j=1;j<=11;j++){
a[i][j]=a[i-1][j]+a[i-1][j-1];
if(a[i][j]<=0){
continue;
}
System.out.print(" "+a[i][j]);
}
System.out.println();
}

}

}
请教,为什么第N行第0列的1都被舍弃了?
运行结果如图:

1
2 1
3 3 1
4 6 4 1
5 10 10 5 1
6 15 20 15 6 1
7 21 35 35 21 7 1
8 28 56 70 56 28 8 1
9 36 84 126 126 84 36 9 1
10 45 120 210 252 210 120 45 10 1

一楼的这样写也不对,这将会在第一行输出两个1

public class YangHui {

public static void main(String[] args){
int [][] a = new int[12] [12];

a[i][0]=1;
a[i][i]=1;
for(int i=2;i<=11;i++){
for(int j=1;j<=11;j++){
System.out.print(a[i][0]);

a[i][j]=a[i-1][j]+a[i-1][j-1];
if(a[i][j]<=0){
continue;
}
System.out.print(" "+a[i][j]);
}
System.out.println();
}

}

}

因为你的 System.out.print(" "+a[i][j]);
这句里的j取不到0,所以第N行第0列的1都被舍弃了
改成这样就行了
package test;

public class YangHui {

public static void main(String[] args){
int [][] a = new int[12] [12];
for(int i=1;i<=11;i++){
a[i][0]=1;
a[i][i]=1;
System.out.print(a[i][0]);
for(int j=1;j<=11;j++){
a[i][j]=a[i-1][j]+a[i-1][j-1];
if(a[i][j]<=0){
conti