1. 程式人生 > >控制檯列印N行楊輝三角,並算出總和

控制檯列印N行楊輝三角,並算出總和

Scanner src = new Scanner(System.in);
System.out.println("請輸入楊輝三角的行數: ");
int total = 0;
int total1 = 0;
int a  =src.nextInt();
//定義一個二維陣列
int[][] str = new int[a][];
for(int i = 0;i<a;i++){
//定義一個數組,用於存放資料
int[] s =new int[i+1];
//給定首尾數字1
s[0] = 1;
s[s.length-1]=1;
//迴圈輸入剩下的數字
for(int j =1;j<s.length-1;j++){
s[j]=str[i-1][j]+str[i-1][j-1];
//累加所的數
total1+=s[j];
}
//把陣列放進二維數組裡充當元素
str[i]=s;

//System.out.println(Arrays.toString(s));
//累加兩邊為一的數
total+=s[0]*2;
}
int c=total-1+total1;
System.out.println("總和為:"+c);
//遍歷二維陣列
for(int a1 = 0;a1<str.length;a1++){
for(int s1=0;s1<str[a1].length;s1++){
System.out.print(str[a1][s1]+" ");
}
System.out.println();
}