设计一个函数def triangle(n):,输出n行杨辉三角形 将下面的完整代码写在答题框内(注释可以省略) import numpy as np # 是否使用numpy模块均可 def triangle(n): # 补充函数代码
import numpy as np
def triangle(n): res = np.zeros((n, n), dtype=int) # 创建一个n*n的二维数组并初始化为0 for i in range(n): res[i][0] = 1 # 每一行的第一个数字都是1 for j in range(1, i+1): res[i][j] = res[i-1][j] + res[i-1][j-1] # 计算杨辉三角形中其他数字 for i in range(n): for j in range(i+1): print(res[i][j], end=' ') # 输出杨辉三角形中的数字 print() # 换行输出
示例输出:
triangle(5)
输出结果:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
设计一个函数def triangle(n):,输出n行杨辉三角形 将下面的完整代码写在答题框内(注释可以省略)
以下是Python3的代码实现:
def triangle(n):
# 创建一个二维列表,用于存储杨辉三角形
tri = [[1]]
# 循环n次,生成n行杨辉三角形
for i in range(1, n):
# 生成当前行的列表
row = [1]
for j in range(1, i):
# 计算当前位置的值
val = tri[i-1][j-1] + tri[i-1][j]
row.append(val)
row.append(1)
# 将当前行添加到二维列表中
tri.append(row)
# 输出杨辉三角形
for row in tri:
print(' '.join(str(val) for val in row).center(n*3))
使用方法:
调用 triangle(n)
函数,其中 n
为要输出的行数。例如,要输出前 5 行杨辉三角形,可以调用 triangle(5)
函数。
用java设计一个函数def triangle(n):,输出n行杨辉三角形 将下面的完整代码写在答题框内(注释可以省略) import numpy as np # 是否使用numpy模块均可 def triangle(n): # 补充函数代码
import java.util.Scanner;
public class YangHuiTriangle { public static void triangle(int n) { int[][] res = new int[n][n]; // 创建一个n*n的二维数组并初始化为0 for (int i = 0; i < n; i++) { res[i][0] = 1; // 每一行的第一个数字都是1 for (int j = 1; j <= i; j++) { res[i][j] = res[i-1][j] + res[i-1][j-1]; // 计算杨辉三角形中其他数字 } } for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { System.out.print(res[i][j] + " "); // 输出杨辉三角形中的数字 } System.out.println(); // 换行输出 } }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入要输出的行数:");
int n = sc.nextInt();
triangle(n);
}
}
// 示例输出: // 请输入要输出的行数:5 // 1 // 1 1 // 1 2 1 // 1 3 3 1 // 1 4 6 4 1
相关推荐












