输入矩阵阶数n,给n阶矩阵的元素按行序由1到n*n顺序赋值,然后将其向右旋转90度,输出旋转后的矩阵
时间: 2023-04-28 21:02:14 浏览: 283
首先,我们需要先创建一个n阶矩阵,并按行序由1到n*n顺序赋值。可以使用两层循环来实现:
matrix = []
num = 1
for i in range(n):
row = []
for j in range(n):
row.append(num)
num += 1
matrix.append(row)
接下来,我们需要将矩阵向右旋转90度。可以先将矩阵转置,然后再将每一行翻转即可:
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(n):
matrix[i].reverse()
最后,我们可以输出旋转后的矩阵:
for row in matrix:
print(row)
完整代码如下:
n = int(input("请输入矩阵阶数:"))
matrix = []
num = 1
for i in range(n):
row = []
for j in range(n):
row.append(num)
num += 1
matrix.append(row)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(n):
matrix[i].reverse()
print("旋转后的矩阵:")
for row in matrix:
print(row)
阅读全文