21xrx.com
2025-04-12 22:54:48 Saturday
文章检索 我的文章 写文章
Java实现杨辉三角
2023-06-16 13:48:11 深夜i     --     --
Java 杨辉三角 代码

杨辉三角也叫帕斯卡三角,是一个数学上著名的数字三角形。它的构造方法很简单,每个数等于它上方两数之和。

下面是Java实现杨辉三角的代码:

public static void main(String[] args) {
  int[][] array = new int[10][];
  for (int i = 0; i < array.length; i++) {
    array[i] = new int[i + 1];
    for (int j = 0; j <= i; j++) {
      if (j == 0 || j == i) {
        array[i][j] = 1;
      } else {
        array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
      }
      System.out.print(array[i][j] + " ");
    }
    System.out.println();
  }
}

以上代码中,我们首先定义了一个二维数组array来存储杨辉三角的数字。然后我们使用两个for循环来遍历这个数组,并使用if-else语句判断每个数应该等于上方两数之和还是等于1。

运行以上代码,你可以得到如下所示的杨辉三角输出:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

  
  

评论区