用JAVA写一个杨辉三角
时间: 2024-05-03 21:23:02 浏览: 95
以下是用Java语言编写的杨辉三角:
```
import java.util.Scanner;
public class YangHuiTriangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int n = input.nextInt();
int[][] triangle = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
```
运行程序后,输入杨辉三角的行数,即可输出相应的杨辉三角。例如,输入6,输出结果如下:
```
请输入杨辉三角的行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
阅读全文