當前位置:編程學習大全網 - 腳本源碼 - java:楊輝三角,輸入n輸出它的前n行

java:楊輝三角,輸入n輸出它的前n行

以下是 Java 代碼,用於生成楊輝三角並輸出前 n 行:

```java

import java.util.Scanner;

public class YangHuiTriangle {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows: ");

int numRows = scanner.nextInt();

for (int i = 0; i < numRows; i++) {

int num = 1;

System.out.printf("%" + (numRows - i) * 2 + "s", ""); // 控制輸出格式

for (int j = 0; j <= i; j++) {

System.out.printf("%4d", num);

num = num * (i - j) / (j + 1); // 計算組合數

}

System.out.println();

}

}

}

```

在這個示例中,我們首先使用 `Scanner` 類讀取用戶輸入的行數 `numRows`。然後,我們使用兩個嵌套的循環來生成楊輝三角。外部循環控制行數,內部循環控制每壹行的元素。

在內部循環中,我們使用了公式 `num = num * (i - j) / (j + 1)` 來計算楊輝三角中的組合數,並使用 `printf()` 方法以規定的格式輸出結果。

最後,我們使用 `%n`(代表換行符)和 `printf()` 方法在控制臺上輸出前 n 行楊輝三角。

例如,在以上程序中輸入 `6`,將會輸出以下結果:

```

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

```

  • 上一篇:現在有沒有在線的書法班啊?在哪能找到?
  • 下一篇:126公司郵箱
  • copyright 2024編程學習大全網