p ython 杨辉三角
时间: 2023-07-11 19:15:06 浏览: 116
以下是 Python 实现的杨辉三角代码,可以输出指定行数的杨辉三角:
```python
def generate_pascal_triangle(num_rows):
triangle = []
for i in range(num_rows):
row = [1] * (i+1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle
n = int(input("请输入行数:"))
pascal_triangle = generate_pascal_triangle(n)
for row in pascal_triangle:
print(row)
```
你可以输入一个正整数作为行数,运行程序后就可以输出对应行数的杨辉三角。
相关问题
p ython 打印杨辉三角
可以使用以下代码来打印杨辉三角:
```python
def generate_triangle(numRows):
triangle = []
for i in range(numRows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
triangle.append(row)
return triangle
def print_triangle(triangle):
max_num = triangle[-1][-1]
max_num_width = len(str(max_num))
for row in triangle:
row_str = ""
for num in row:
num_str = str(num).center(max_num_width)
row_str += num_str + " "
print(row_str.center(len(row_str) + max_num_width))
numRows = 5
triangle = generate_triangle(numRows)
print_triangle(triangle)
```
这个程序将打印一个包含 `numRows` 行的杨辉三角形。输出结果如下所示:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
j ava杨辉三角完整
以下是Java实现的杨辉三角完整代码:
```java
import java.util.Scanner;
public class YangHuiTriangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int n = input.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
```
运行结果:
```
请输入杨辉三角的行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
阅读全文