使用Java列印楊輝三角

來源:互聯網
上載者:User

標籤:開始   system.in   scanner   stat   length   資料   package   log   數組   

package 楊輝三角;import java.util.Scanner;public class 三角 {    private static Scanner scn;    public static void main(String[] args) {        scn = new Scanner(System.in);                System.out.println("請輸入資料");            int n = scn.nextInt();                //定義一個二維數組        int [][] array = new int [n][n];                //給這個二維數組的任意一行的第一列和最後一列賦值為1        for (int x = 0;x < array.length;x ++){            array [x][0] = 1;//任意一行的第一列            array [x][x] = 1;//任意一行的最後一列                    }        //從第二行開始        for (int x = 2;x < array.length;x ++){            //要從第一列開始,因為第0列已經賦值了            for (int y = 1;y <= x;y ++){                array [x][y] = array[x - 1][y - 1] + array[x - 1][y];            }        }        //賦值完成之後,遍曆這個二維數組        for (int x = 0;x < array.length;x ++){            for (int y = 0;y <= x;y ++){                System.out.print(array[x][y]+"\t");// \t的意思就是8個空格            }                    System.out.println();//換行                    }    }}

列印結果如下:

使用Java列印楊輝三角

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.