java输出杨辉三角居中
时间: 2024-05-24 10:06:59 浏览: 129
要在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 < rows - i - 1; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
```
运行以上代码,输入要打印的行数,即可输出杨辉三角形,居中显示。
阅读全文