用JAVA写一个杨辉三角
时间: 2024-06-04 09:13:19 浏览: 46
好的,以下是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[][] nums = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
nums[i][j] = 1;
} else {
nums[i][j] = nums[i - 1][j - 1] + nums[i - 1][j];
}
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
}
希望能帮到你!如果还有其他问题,请随时问我。
相关问题
用java写一个杨辉三角
下面是 Java 代码实现的杨辉三角:
```
import java.util.ArrayList;
import java.util.List;
public class PascalTriangle {
public static void main(String[] args) {
int rows = 5;
List<List<Integer>> result = generate(rows);
for (List<Integer> row : result) {
for (Integer num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if (numRows == 0) {
return result;
}
List<Integer> firstRow = new ArrayList<>();
firstRow.add(1);
result.add(firstRow);
for (int i = 1; i < numRows; i++) {
List<Integer> prevRow = result.get(i - 1);
List<Integer> currRow = new ArrayList<>();
currRow.add(1);
for (int j = 1; j < i; j++) {
currRow.add(prevRow.get(j - 1) + prevRow.get(j));
}
currRow.add(1);
result.add(currRow);
}
return result;
}
}
```
用java写一个杨辉三角形
以下是用Java写一个杨辉三角形的示例代码:
```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[][] arr = new int[n][n];
// 初始化第一列和对角线为1
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();
}
}
}
```
运行结果如下:
```
请输入杨辉三角形的行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 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)
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)