[Java]打印杨辉三角,对于维数可用户自定义

来源:互联网 发布:js鼠标悬停事件实例 编辑:程序博客网 时间:2024/05/16 08:46
  1. /*
  2.    * Quiz1
  3.    *
  4.    * 打印杨辉三角,对于维数可用户自定义。
  5.    *
  6.    * 2008年12月13日
  7.    *
  8.    * (Cason_xu)
  9.    */
  10. import java.util.Scanner;
  11. class Quiz1 {
  12.     public static void main(String[] args) {
  13.     
  14.         Scanner sc = new Scanner(System.in);
  15.         System.out.print("请输入你所需的杨辉三角的维数:");
  16.         int  n = sc.nextInt();
  17.         int[] [] array = new int [n] [];
  18.         
  19.         //杨辉三角每行的元素个数
  20.         for (int i = 0; i < array.length; i++) {
  21.             array[i] = new int [i + 1];
  22.         }
  23.         
  24.         //初始化
  25.         array[0] [0] = 1;
  26.         array[1] [0] = 1;
  27.         array[1] [1] = 1;
  28.         for (int i = 2; i < array.length; i++) {
  29.             array[i] [0] = 1;
  30.             array[i] [i] = 1;
  31.             for (int j = 1;j < i; j++) {
  32.              array[i] [j] = array[i - 1] [j - 1] + array[i - 1] [j];
  33.             }
  34.         }
  35.         
  36.         //打印输出
  37.         for (int i = 0; i < array.length;i++){
  38.             for (int j = 0; j < array[i].length ; j++) {
  39.                 System.out.print(array[i] [j] + "/t");
  40.             } 
  41.             System.out.println();
  42.         }   
  43.     }
  44. }