检验并打印幻方矩阵。在下面的5×5阶幻方矩阵中,每一行、每一列、每一对角线上的元素之和都是相等的,试编写程序将下面这个矩阵中的元素存储到一个二维整型数组中,然后检验其是否为幻方矩阵,并将其按如下格式显示到屏幕上。 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 输出格式: 如果是幻方矩阵,输出提示信息: "It is a magic square!\n",并输出矩阵元素,输出格式为: "%4d"(换行使用"\n") 如果不是幻方矩阵,输出提示信息: "It is not a magic square!\n" (不输出矩阵元素)
时间: 2024-03-24 15:40:07 浏览: 58
以下是Python实现代码:
```python
matrix = [[17, 24, 1, 8, 15],
[23, 5, 7, 14, 16],
[4, 6, 13, 20, 22],
[10, 12, 19, 21, 3],
[11, 18, 25, 2, 9]]
# 检验行和列的和是否相等
n = len(matrix)
row_sum = [sum(matrix[i]) for i in range(n)]
col_sum = [sum(matrix[i][j] for i in range(n)) for j in range(n)]
if row_sum == col_sum:
# 检验主对角线和副对角线的和是否相等
main_diag_sum = sum(matrix[i][i] for i in range(n))
sub_diag_sum = sum(matrix[i][n-i-1] for i in range(n))
if main_diag_sum == sub_diag_sum == row_sum[0]:
print("It is a magic square!")
for i in range(n):
for j in range(n):
print("%4d" % matrix[i][j], end="")
print("")
else:
print("It is not a magic square!")
else:
print("It is not a magic square!")
```
输出结果为:
```
It is a magic square!
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
```
阅读全文