帮我用java语言写一个5行的杨辉三角
时间: 2023-05-30 11:04:47 浏览: 72
很高兴为您提供帮助,以下是使用Java语言编写的5行杨辉三角代码:
```java
public class YangHuiTriangle {
public static void main(String[] args) {
int[][] nums = new int[5][5];
for (int i = 0; i < 5; i++) {
nums[i][0] = 1;
nums[i][i] = 1;
for (int j = 1; j < i; j++) {
nums[i][j] = nums[i - 1][j] + nums[i - 1][j - 1];
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
}
```
输出结果为:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
希望能帮助到您,如有疑问请随时提出。
相关问题
用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];
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
```
输入行数后,程序会输出对应的杨辉三角。
用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[][] triangle = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
```
运行程序后,输入杨辉三角的行数,即可输出相应的杨辉三角。例如,输入6,输出结果如下:
```
请输入杨辉三角的行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)