用java輸出楊輝三角


楊輝三角:它的兩個邊都是1,內部其它都是肩上兩個數的和

第一種:

package aaa;

public class YangHui {

	public static void main(String[] args) {
		/**
		 * 6行6列的楊輝三角
		 */
		int row = 6;//行數
		int[][] yanghui = new int[row][row];//6行6列數組
		
		for (int i = 0; i < row; i++){//行
			for(int j = 0;j<= i;j++){//列
				if (j==0 || j==i){
					yanghui[i][j]=1;
					
				}else{
					yanghui[i][j]=yanghui[i-1][j-1]+yanghui[i-1][j];
				}
				System.out.print(yanghui[i][j]+" ");
			}
			System.out.println();
		}	
	}
}

第二種:等腰三角形

package aaa;

public class YangHui {

	public static void main(String[] args) {
		/**
		 * 8行8列的楊輝三角
		 */
		int row = 6;//行數
		int[][] yanghui = new int[row][row];//6行6列數組
		
		for (int i = 0; i < row; i++){//行
			for(int j = 0;j<= i;j++){//列
				if (j==0 || j==i){
					yanghui[i][j]=1;
					
				}else{
					yanghui[i][j]=yanghui[i-1][j-1]+yanghui[i-1][j];
				}
//				System.out.print(yanghui[i][j]+" ");
			}
//			System.out.println();
		}
//等腰輸出處理
		for (int i = 0; i < row; i++){
			int num = row -i;
			for(int j = 0;j<= num;j++){
				System.out.print(" ");	
		}
			for(int k= 0;k<= i;k++){
				System.out.print(yanghui[i][k]+" ");	
		}
			System.out.println();
	}
	
	}
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM