[JavaSE]楊輝三角

//楊輝三角
import java.util.Scanner;//導包
public class Ex003{
	public static void main(String[] args) 
	{
		Scanner sc = new Scanner(System.in);//new 一個 Scanner的對象
		System.out.print("input x:");
		int x = sc.nextInt();//讓x接收一個整型的變量
		int[][] arr = new int[x][x];//new一個整型的二維數組用來存放楊輝三角各個座標爲的值
		for(int i = 0;i < x;i++){
			for(int j = x-1; j > i; j--){
				System.out.print(" ");//數值前的空格
			}
			for(int j = 0; j <= i; j++){
				if(i==j || j==0){
					arr[i][j] = 1;//每行第一個和最後一個值爲1
				}else{
					arr[i][j] = arr[i-1][j-1]+arr[i-1][j];//出去每行第一個和最後一個 當前值爲左上角和上方值得和
				}
				System.out.print(arr[i][j]+" ");//輸出
			}
			System.out.println();//每行換行
		}	
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章