编程:打印杨辉三角前10行。
时间: 2024-04-29 11:27:13 浏览: 18
好的,以下是打印杨辉三角前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, coef = 1, space, i, j;
printf("请输入行数: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (space = 1; space < rows - i; space++)
printf(" ");
for (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;
}
```
这段代码会先让用户输入杨辉三角形的行数,然后使用两个嵌套的循环来打印出整个三角形。在内部的循环中,我们计算出当前位置需要打印的数字,然后使用`printf`函数来打印它,同时为了使输出对齐,我们使用了`%4d`格式化字符串。最后,我们在每一行的末尾打印一个换行符,以便下一行的输出能够正确对齐。
希望这段代码能够帮到你!
使用python编程打印出杨辉三角形前10行
以下是python编程打印出杨辉三角形前10行的代码:
```
def yanghui_triangle(n):
triangle = [[1]]
for i in range(1, n):
row = [1]
for j in range(1, i):
row.append(triangle[i-1][j-1] + triangle[i-1][j])
row.append(1)
triangle.append(row)
return triangle
for row in yanghui_triangle(10):
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]
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)