编程打印杨辉三角的前十行
时间: 2023-07-02 17:11:02 浏览: 57
以下是使用Python语言打印杨辉三角前十行的代码:
```python
n = 10 # 杨辉三角的行数
triangle = [] # 存储杨辉三角的列表
for i in range(n):
row = [1] * (i + 1) # 初始化每一行的第一个和最后一个数为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(" ".join(str(num) for num in 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
```
相关问题
编程:打印杨辉三角前10行。
好的,以下是打印杨辉三角前10行的Python代码:
```
def yanghui_triangle(n):
if n == 1:
return [1]
else:
last_row = yanghui_triangle(n-1)
row = [1]
for i in range(n-2):
row.append(last_row[i] + last_row[i+1])
row.append(1)
return row
for n in range(1, 11):
print(" ".join(str(x) for x in yanghui_triangle(n)))
```
输出结果如下:
```
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 rows = 6;
int triangle[rows][rows];
// 初始化杨辉三角
for (int i = 0; i < rows; 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];
}
}
}
// 打印杨辉三角
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; 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
```
相关推荐
![](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)