打印杨辉三角10行代码
时间: 2024-02-16 07:04:13 浏览: 48
好的,以下是打印杨辉三角前十行的 Python 代码:
```python
n = 10
triangle = []
for i in range(n):
row = []
for j in range(i + 1):
if j == 0 or j == i:
row.append(1)
else:
row.append(triangle[i - 1][j - 1] + triangle[i - 1][j])
triangle.append(row)
for row in triangle:
print(' '.join([str(num) for num in row]))
```
这段代码利用了二维列表来存储杨辉三角的每一行,然后在循环中计算每个元素的值,并将其添加到当前行的列表中。最后,使用另一个循环来打印整个杨辉三角。
相关问题
用c语言打印杨辉三角10行
以下是使用C语言打印杨辉三角10行的代码:
```c
#include <stdio.h>
int main() {
int rows = 10;
int coef = 1;
for (int i = 0; i < rows; i++) {
for (int space = 1; space < rows - i; space++) {
printf(" ");
}
for (int j = 0; j <= i; j++) {
if (j == 0 || i == 0) {
coef = 1;
} else {
coef = coef * (i - j + 1) / j;
}
printf("%4d", coef);
}
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
```
用python打印杨辉三角形10行
好的,以下是用 Python 打印杨辉三角形的代码,可以打印10行:
```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 i in range(n):
# 左侧对齐
print('{:>{}}'.format('', (n - i) * 2), end='')
for j in range(i + 1):
print('{:^4}'.format(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
```
阅读全文
相关推荐













