java基础编程60题之33

package com.xijiaopractice;


import java.util.Scanner;


public class Test33 {
/*题目:打印出杨辉三角形(要求打印出 10行如下图)
         1
       1   1
     1  2  1
   1 3 3 1
 1  4  6  4  1
1 5 10 10 5 1
…………
*/




public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
while(scn.hasNext()){
int m=scn.nextInt();
printYangHui(m);
}
}
public static void printYangHui(int n){
if(n==1){
//System.out.println(" "+1+" ");
return;
}
int[][] a=new int[n][2*n];
a[0][n]=1;
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a[0].length-2; j++) {
a[i+1][j+1]=a[i][j]+a[i][j+2];
}
}
a[a.length-2][a[0].length-2]=1;
a[a.length-1][a[0].length-1]=1;
for (int i = 1; i < a.length; i++) {
boolean flag=true;
for (int j = 0; j < a[0].length; j++) {
if(a[i][j]==0){
//System.out.printf("%4s"," ");
//System.out.print(" ");
}else {
if(flag){
flag=false;
System.out.print(a[i][j]);

}else{
System.out.print(" "+a[i][j]);
}
//System.out.print(a[i][j]);
}

}
System.out.println();
}

}
}

猜你喜欢

转载自blog.csdn.net/m0_38068868/article/details/81061977
今日推荐