我试图创建一个程序来检查给定的矩阵是否是幻方。幻方是指在垂直、水平和对角线方向上每个序列中所有数字的总和是相同的。
不管我输入的数字是什么组合,它总是返回魔方为真。
编辑:固定对角线(kinda),除了它输出额外的信息和对角线。

#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>

int main()
{
int nRows;
int nCols;
int sumR;
int sumC;
int sumD = 0;
int sumD2 = 0;
int k;
int p;
//bool isMagic = 1;


//Defining Matrix order
printf("Enter number of Rows: \n");
scanf("%i",&nRows);


printf("Enter number of Columns: \n");
scanf("%i",&nCols);

int matrix[nRows][nCols];
//int SumR[nRows];
//sint SumC[nCols];

//Enterring Coefficients of the Matrix
for(k = 0; k < nRows; ++k){
    for(p = 0; p < nCols; ++p){
        printf("Enter value for Matrix[%i][%i]: ",k,p);

        scanf("%i",&matrix[k][p]);
    }
}


//Adding diagonal elements
for(k = 0; k < nRows; ++k){
    //for(p = 0; p < nCols; ++p){
        //if(k == p ){
            sumD = sumD + matrix[k][k];
            sumD2 = sumD2 + matrix[k][nCols - k - 1];
            //sumD2 += matrix[k]
        //}
    //}
    printf("Sum of the Diagonals = %i\n",sumD);
    printf("Sum of the Diagonals2 = %i\n",sumD2);
    //sumD2 = 0;
    //sumD = 0;

}


//Adding the rows
for(k = 0; k < nRows; ++k){
    for(p = 0; p < nCols; ++p){
        sumR += matrix[k][p];
    }
    printf("Sum of the %i row is = %i\n",k,sumR);
    //if(sumR != sumC)
        //isMagic = 0;
    sumR = 0;
}

//Adding the columns
for(p = 0; p < nRows; ++p){
    for(k = 0; k < nCols; ++k){
        sumC += matrix[k][p];
    }
    printf("Sum of the %i column is = %i\n",p,sumC);
    //if(sumC != sumR)
        //isMagic = 0;
    sumC = 0;

}


//Displaying matrix
for(k = 0; k < nRows; ++k){
    for(p = 0; p < nCols; ++p){
    printf("%i\t",matrix[k][p]);
}
printf("\n");
}



if(sumR == sumC == sumD == sumD2){
    printf("\nMagic Square!\n");
}
else{
    printf("\nNot a Magic Square!\n");
}


return 0;
//col[n]+row[n] == userinput

}

最佳答案

最好的方法是假设它是一个魔法矩阵。定义新变量

int isMagic = 1;

得到对角线的和。把它放进sumD。
然后,将sumR=0替换为
if (sumR != sumD ) isMagic = 0;

sumC=0;由
if (sumC != sumD ) isMagic = 0;

还有魔法!
if( isMagic) {
    printf("\nMagic Square!\n");
}
else{
    printf("\nNot a Magic Square!\n");}

09-06 19:28