Java寫出楊輝三角

記得楊輝三角最早的時候出現是在初中的時候,
不知道的你可以百度一下,

下面就是楊輝三角:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 5 1
……

通過上邊的樣例,可以得出下面的特徵。
楊輝三角最重要的公式就是:arr[x][y] = arr[x- -][y- -] + arr[x- -][y]

所以我們才能根據這個公式寫出下面的代碼:

import java.util.*;

public class yanghuiTrangle
{
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入楊輝三角的層數:");
        int n = scanner.nextInt();//楊輝三角的行數
        int[][] arr = new int[30][30];
        for(int x=0;x<n;x++){
            arr[x][0] = 1;
            for(int y=0;y<=x;y++){
                if(y<x){
                    System.out.print((arr[x-1][y-1] + arr[x-1][y]) + " ");
                    //不要使用x--操作,否則會報出數組下標越界異常。
                }else{
                    System.out.println(arr[x-1][y-1] + arr[x-1][y]);
                }
            }
        }
        System.out.println();
    }   
}

這就是我根據楊輝三角的公式寫出的代碼,有不同意見的可以與我發郵件私聊。

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