Check and print the magic square matrix (4 points)
Question content:
A magic square matrix means that the sum of the elements in each row, column, and diagonal of the matrix is equal. Input a 5×5 matrix from the keyboard and store it in a two-dimensional integer array, check whether it is a magic square matrix, and display it on the screen in the specified format.
Input format: “%d”
Output format:
If it is a magic square matrix, output the prompt message: "It is a magic square!\n"
Output of matrix elements: "%4d" (use "\n" for newline)
If it is not a magic square matrix, output the prompt message: "It is not a magic square!\n"
Input example 1:
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
("_" in the input example represents a space)
Output sample 1:
It is a magic square!
172418**15
235714**16
461320**22
10121921***3
1118252**9
("*" in the output sample represents a space)
Input example 2:
1_0_1_6_1
3_1_1_1_1
1_1_1_1_2
1_1_1_1_1
9_1_7_1_1
("_" in the input example represents a space)
Output sample 2:
It is not a magic square!
Note: To avoid format errors, please directly copy and paste the input and output prompt information and format control strings given above!
("_" in the input sample represents a space, and "*" in the output sample represents a space)
#include<stdio.h>
int main(){
int array[5][5]={
0},burray[10]={
0};
int m=0,n=0,q=0,rsum=0,lsum=0;
/* 获取二维数组 */
for(int x=0;x<5;x++)
{
for(int y=0;y<5;y++)
{
scanf("%d",&array[x][y]);
}
}
/* end */
for( m=0;m<5;m++)
{
for( n=0;n<5;n++)
{
burray[q]+=array[m][n];//计算每行和,q=0,1,2,3,4
if(m==n)
rsum+=array[m][n];//一条对角线(m=n)和
if(m+n==4)
lsum+=array[m][n];//另外一条对角线和
//printf("%d ",array[m][n]);
}
q++;
for(int q=0;q<5;q++)
{
burray[5+q]+=array[m][q];//计算每列和
}
//printf("\n %d %d %d %d %d ",array[m][0],array[m][1],array[m][2],array[m][3],array[m][4]);
}
int xx=0;
if(lsum==rsum)//在两条对角线和相等情况下,判断行,列和
{
for( xx=1;xx<10;xx++)
{
if(burray[0]!=burray[xx]) //printf("\n%d\n",burray[xx]);
break;
}
}
else
{
printf("It is not a magic square!\n");
return 0;
}
if(xx==10)
{
printf("It is a magic square!\n");
for(int x=0;x<5;x++)
{
for(int y=0;y<5;y++)
{
printf("%4d",array[x][y]);//输出二维数组
}
printf("\n");
}
}
else
printf("It is not a magic square!\n");
return 0;
}