我正在尝试编写一个for语句,该语句一次对二维数组的行和列进行汇总,并确定所有总和是否相同。我已经做了以下事情,但我无法弄清楚我做错了什么。
public static int isMagic(int mat[][])
{
int row = mat.length;
int col = mat[0].length;
int sum = row + col;
if(row == col)
{
System.out.println("The matrix is a magic square.");
}
else
{
System.out.println("The matrix is not a magic square.");
}
return sum;
for(int sumR = 0; sumR < mat.length; sumR++)
{
int total = 0;
for(int sumC = 0; sumC < mat[sumR].length; sumC++)
{
total += mat[sumR][sumC];
if(sumR == 34 && sumC == 34)
{
System.out.println("The sum of all rows and columns is 34.");
}
else
{
System.out.println("The matrix is not a magic square.");
}
}
return total;
}
}
矩阵的示例。
1 2 34 5 67 8 9
你总是返回变量 sum(行 + col),它永远不会到达循环。只需删除第一个 return 语句,它应该可以工作。
我不建议你使用sum变量作为索引。也许做这样的事情:
for(int r = 0; r < mat.length; r++){
for(int c = 0; c < mat.length; c++){
sumC = sumC + mat[r][c];
}
}