用java编写出杨辉三角形
时间: 2023-10-16 18:29:12 浏览: 152
yanghuisanjiao.rar_java 打印 杨辉三角
以下是用Java编写的杨辉三角形代码:
```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();
}
scanner.close();
}
}
```
运行程序后,输入杨辉三角形的行数,程序会输出相应行数的杨辉三角形。例如,输入6,输出如下:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
阅读全文