java 输入n,输出n行杨辉三角。
时间: 2023-05-19 19:03:50 浏览: 75
以下是 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[][] triangle = new int[n][n];
for (int i = 0; i < n; i++) {
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
```
输入样例:
```
请输入要输出的行数:5
```
输出样例:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
阅读全文