打印出以下的杨辉三角形(要求打印出10行)。 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
时间: 2024-01-07 21:04:53 浏览: 62
以下是 Python 代码实现:
```python
n = 10
triangle = []
for i in range(n):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
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行)。 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 ……
好的,以下是用C语言打印出10行杨辉三角形的代码:
```
#include <stdio.h>
int main() {
int numRows = 10;
int triangle[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];
}
printf("%d ", triangle[i][j]);
}
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
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行: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
好的,下面是C语言代码实现杨辉三角形的前10行:
```
#include <stdio.h>
int main() {
int row, col;
int arr[10][10];
// 初始化第一列和对角线
for (row = 0; row < 10; row++) {
arr[row][0] = 1;
arr[row][row] = 1;
}
// 计算其余的数值
for (row = 2; row < 10; row++) {
for (col = 1; col < row; col++) {
arr[row][col] = arr[row-1][col-1] + arr[row-1][col];
}
}
// 打印杨辉三角形
for (row = 0; row < 10; row++) {
for (col = 0; col <= row; col++) {
printf("%d ", arr[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
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
```
阅读全文