帮我用java打印出杨辉三角的代码
时间: 2023-02-21 10:01:45 浏览: 63
好的,这是一份用Java语言打印杨辉三角的代码:
```
import java.util.Scanner;
public class PascalTriangle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int rows = scan.nextInt();
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
```
运行结果示例:
```
请输入杨辉三角的行数:5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
相关问题
用java打印出杨辉三角
以下是使用Java打印杨辉三角的代码:
```java
import java.util.Scanner;
public class YangHuiTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int n = sc.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
arr[i][0] = 1;
arr[i][i] = 1;
}
for (int i = 2; i < n; i++) {
for (int j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
```
运行程序后,会提示用户输入杨辉三角的行数,例如输入5,则程序会输出如下结果:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
java 打印出杨辉三角形
下面是 Java 实现的杨辉三角形打印代码:
```java
import java.util.Scanner;
public class YangHuiTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入杨辉三角形的行数:");
int n = sc.nextInt(); // 获取输入的行数
int[][] arr = new int[n][n]; // 创建二维数组保存杨辉三角形数据
// 计算杨辉三角形的数值
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
}
}
// 打印杨辉三角形
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
```
运行结果:
```
请输入杨辉三角形的行数:5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)