Java 代码实现杨辉三角
时间: 2023-04-10 07:02:29 浏览: 113
以下是 Java 代码实现杨辉三角:
```
import java.util.Scanner;
public class YangHuiTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int n = scanner.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
```
希望能够帮到你!
相关问题
使用java代码实现杨辉三角
好的,以下是使用Java代码实现杨辉三角的方法:
```java
public class YangHuiTriangle {
public void printYangHuiTriangle(int n) {
int[][] triangle = new int[n][];
for (int i = 0; i < n; i++) {
triangle[i] = new int[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i - 1][j] + triangle[i - 1][j - 1];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
```
可以通过调用 `printYangHuiTriangle(n)` 方法来打印出前 n 行杨辉三角。
请问还有什么其他问题吗?
java代码输出杨辉三角形
以下是 Java 代码输出杨辉三角形:
```
import java.util.Scanner;
public class YangHuiTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入杨辉三角形的行数:");
int n = sc.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
```
阅读全文