用数组的方法编写杨辉三角前十行
时间: 2023-07-17 09:33:10 浏览: 51
好的,下面是用数组的方法编写杨辉三角前十行的代码:
```python
n = 10 # 控制行数
triangle = [[1] * (i+1) for i in range(n)] # 创建二维列表,初始化为1
# 计算杨辉三角
for i in range(2, n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
# 输出结果
for i in range(n):
print(' ' * (n-i), end='')
for j in range(i+1):
print(triangle[i][j], end=' ')
print()
```
输出结果如下:
```
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语言用二维数组编写杨辉三角的前七行
以下是C语言使用二维数组编写杨辉三角的前七行的代码:
```c
#include <stdio.h>
int main()
{
int row, col;
int triangle[7][7] = {0};
// 初始化第一行
triangle[0][0] = 1;
// 计算杨辉三角
for (row = 1; row < 7; row++) {
for (col = 0; col <= row; col++) {
if (col == 0 || col == row) {
triangle[row][col] = 1;
} else {
triangle[row][col] = triangle[row-1][col-1] + triangle[row-1][col];
}
}
}
// 输出杨辉三角
for (row = 0; row < 7; row++) {
for (col = 0; col <= row; col++) {
printf("%d ", triangle[row][col]);
}
printf("\n");
}
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
```
用c语言一维数组编写十行杨辉三角
Sure, here's the code to generate the first ten rows of Pascal's triangle using a one-dimensional array in C:
```
#include <stdio.h>
int main() {
int n = 10;
int row[n], i, j;
for (i = 0; i < n; i++) {
row[i] = 1;
for (j = i - 1; j > 0; j--) {
row[j] += row[j - 1];
}
for (j = 0; j < i + 1; j++) {
printf("%d ", row[j]);
}
printf("\n");
}
return 0;
}
```
This program will generate the first ten rows of Pascal's triangle using only a one-dimensional array for storage. Hope that helps!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)