杨辉三角

杨辉三角

打印10行杨辉三角
1.打印出直角杨辉三角

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

运行结果:

2.在各行前加上相应空格

public class Yanghui {
    public static void main(String[] args) {
        int[][] a = new int[10][10];
        for(int i=0;i<10;i++){
            for(int j=0;j<=i;j++){
                if(j==0||i==j){
                    a[i][j]=1;
                }else{
                    a[i][j]=a[i-1][j-1]+a[i-1][j];
                }
                
            }
            
        }
//加空格
        for(int i=0;i<10;i++){
            for(int k=0;k<2*(10-i);k++){
                System.out.print(" ");
            }
            for(int j=0;j<=i;j++){
                System.out.print(a[i][j]+"   ");
            }
            System.out.println();
        }
    }
}

最终运行结果:

posted on 2021-04-21 21:43  久先生  阅读(62)  评论(0)    收藏  举报