java读入一个整数n,输出杨辉三角形的前10行,
时间: 2023-05-28 16:04:14 浏览: 100
以下是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[][] triangle = new int[n][n];
// 初始化第一行和对角线为1
for (int i = 0; i < n; i++) {
triangle[i][0] = 1;
triangle[i][i] = 1;
}
// 计算其他元素
for (int i = 2; i < n; i++) {
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();
}
}
}
```
运行结果:
```
请输入要输出的杨辉三角行数:10
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
```
阅读全文