Java打印杨辉三角
时间: 2024-04-08 17:26:30 浏览: 70
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 rows = scanner.nextInt();
int[][] triangle = new int[rows][];
for (int i = 0; i < rows; i++) {
triangle[i] = new int[i + 1];
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 < rows; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
```
运行以上代码,输入杨辉三角的行数,即可打印出相应行数的杨辉三角。
阅读全文