编写程序,打印杨辉三角形的前10行
时间: 2023-09-13 08:05:25 浏览: 65
好的,以下是打印杨辉三角形前10行的 Python 代码:
```python
n = 10
triangle = []
# 初始化杨辉三角形的第一行
triangle.append([1])
# 逐行构建杨辉三角形
for i in range(1, n):
# 当前行的列表
row = []
# 上一行的列表
prev_row = triangle[i-1]
# 左侧的数字
row.append(1)
# 中间的数字
for j in range(1, i):
row.append(prev_row[j-1] + prev_row[j])
# 右侧的数字
row.append(1)
# 将当前行添加到杨辉三角形中
triangle.append(row)
# 打印杨辉三角形
for row in triangle:
print(row)
```
输出结果:
```
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
```
相关问题
编写c++程序,打印杨辉三角形的前10行
好的,以下是打印杨辉三角形前10行的 C++ 代码:
```c++
#include <iostream>
using namespace std;
int main() {
const int n = 10;
int triangle[n][n];
// 初始化杨辉三角形的第一行
triangle[0][0] = 1;
// 逐行构建杨辉三角形
for (int i = 1; i < n; i++) {
// 左侧的数字
triangle[i][0] = 1;
// 中间的数字
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
// 右侧的数字
triangle[i][i] = 1;
}
// 打印杨辉三角形
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
cout << triangle[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
```
用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 numRows = scanner.nextInt();
int[][] triangle = new int[numRows][numRows];
for (int i = 0; i < numRows; 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();
}
scanner.close();
}
}
```
输入一个整数作为行数,输出相应的杨辉三角形。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)