用IDEA写出杨辉三角
时间: 2024-05-03 20:23:24 浏览: 65
```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][]; //创建二维数组
for (int i = 0; i < n; i++) {
triangle[i] = new int[i + 1]; //每一行的列数为i+1
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1; //第一列和最后一列为1
} else {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; //其他位置为上一行两个数之和
}
System.out.print(triangle[i][j] + " "); //输出当前位置的数
}
System.out.println(); //换行
}
}
}
```
输出示例:
```
请输入杨辉三角的行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
阅读全文