日期:2014-05-20  浏览次数:20690 次

用java编写杨辉三角,打印的结果应该是空的部分怎么是0?
import java.util.*;
public class YanghuiSanjiao {
public static void main(String []args){
System.out.println("请输入行数:");
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int [][]sanjiao=new int[N][N];
int x,y=0;
sanjiao[0][0]=sanjiao[1][0]=sanjiao[1][1]=1;
for(x=2;x<sanjiao.length;x++){
sanjiao[x][0]=sanjiao[x][x]=1;
for(y=1;y<sanjiao[x].length;y++){
if(x==y){
sanjiao[x][y]=1;
}
else if(y<x){
sanjiao[x][y]=sanjiao[x-1][y-1]+sanjiao[x-1][y];
}

}
}
for( x=0;x<sanjiao.length;x++){
for( y=0;y<sanjiao[x].length;y++){
System.out.print(sanjiao[x][y]+" ");

}
System.out.println();
}

}

}


结果:
1 0 0 0 0 0 0 
1 1 0 0 0 0 0 
1 2 1 0 0 0 0 
1 3 3 1 0 0 0 
1 4 6 4 1 0 0 
1 5 10 10 5 1 0 
1 6 15 20 15 6 1

------解决方案--------------------
你数组里是零就是零呗

for( x=0;x<sanjiao.length;x++){
 for( y=0;y<sanjiao[x].length;y++){
 System.out.print(sanjiao[x][y]+" ");

 }
 System.out.println();
 }

System.out.print(sanjiao[x][y]+" ");
这句 改成 

if(sanjiao[x][y]!=0)System.out.print(sanjiao[x][y]+" ");
Java code

import java.util.*;
public class YanghuiSanjiao {
public static void main(String []args){
 System.out.println("请输入行数:");
 Scanner sc=new Scanner(System.in);
 int N=sc.nextInt();
 int [][]sanjiao=new int[N][N];
 int x,y=0;
 sanjiao[0][0]=sanjiao[1][0]=sanjiao[1][1]=1;
 for(x=2;x<sanjiao.length;x++){
 sanjiao[x][0]=sanjiao[x][x]=1;
 for(y=1;y<sanjiao[x].length;y++){
 if(x==y){
 sanjiao[x][y]=1;
 }
 else if(y<x){
 sanjiao[x][y]=sanjiao[x-1][y-1]+sanjiao[x-1][y];
 }

 }
 }
 for( x=0;x<sanjiao.length;x++){
 for( y=0;y<sanjiao[x].length;y++){
if(sanjiao[x][y]!=0)System.out.print(sanjiao[x][y]+" ");

 }
 System.out.println();
 }

 }

 }