二维数组对角线和
2D array diagonal sum
所以我正在尝试对对角线求和并将其与魔术常数进行比较。如果它们相同,那么它就是一个幻方。我能够为对角线编写代码,但它显示的结果不正确。我的代码在这里:
public static boolean checkDiagonals(int[][] array, int magicConstant){
int total = 0;
int wrong = 0;
for(int i = 0; i < array.length; i++){
total= total + array[i][i] + array[array.length - i-1][array.length - i-1];
}
if(total!=magicConstant){
wrong++;
}
System.out.println("There were " + wrong + " invalid diagnals.");
return wrong == 0;
}
我的输出是这样的
Size: 3
1 1 1
5 5 5
9 9 9
1 1 1
5 5 5
9 9 9
The magic constant is 15
There were 1 invalid diagnals.
This is NOT a magic square.
Size: 3
8 1 6
3 5 7
4 9 2
8 1 6
3 5 7
4 9 2
The magic constant is 15
There were 1 invalid diagnals.
This is NOT a magic square.
正确的输出应该显示第二个是魔方但是我的程序说它不是。
为什么我认为我的代码有问题是因为我得到每个方块的 There were 1 invalid diagnals.
所以这里有问题。
编辑
我在获得正确的输出时遇到问题。我相信这与添加对角线有关 为什么它一直为每个正方形打印 1 个无效对角线。我显示的输出仅适用于 2 个方块,但是当我尝试使用其他方块时,它会继续打印 1 invalid diagonal
.
更多详情见评论讨论:
public static boolean checkDiagonals(int[][] array, int magicConstant){
int total1 = 0;
int total2 = 0;
int wrong = 0;
for(int i = 0; i < array.length; i++){
total1= total1 + array[i][i];
total2 = total2 + array[array.length - i-1][array.length - i-1];
}
if(total1!=magicConstant){
wrong++;
}
if(total2!=magicConstant){
wrong++;
}
System.out.println("There were " + wrong + " invalid diagnals.");
return wrong == 0;
}
所以我正在尝试对对角线求和并将其与魔术常数进行比较。如果它们相同,那么它就是一个幻方。我能够为对角线编写代码,但它显示的结果不正确。我的代码在这里:
public static boolean checkDiagonals(int[][] array, int magicConstant){
int total = 0;
int wrong = 0;
for(int i = 0; i < array.length; i++){
total= total + array[i][i] + array[array.length - i-1][array.length - i-1];
}
if(total!=magicConstant){
wrong++;
}
System.out.println("There were " + wrong + " invalid diagnals.");
return wrong == 0;
}
我的输出是这样的
Size: 3
1 1 1
5 5 5
9 9 9
1 1 1
5 5 5
9 9 9
The magic constant is 15There were 1 invalid diagnals.
This is NOT a magic square.
Size: 3
8 1 6
3 5 7
4 9 2
8 1 6
3 5 7
4 9 2
The magic constant is 15There were 1 invalid diagnals.
This is NOT a magic square.
正确的输出应该显示第二个是魔方但是我的程序说它不是。
为什么我认为我的代码有问题是因为我得到每个方块的 There were 1 invalid diagnals.
所以这里有问题。
编辑
我在获得正确的输出时遇到问题。我相信这与添加对角线有关 为什么它一直为每个正方形打印 1 个无效对角线。我显示的输出仅适用于 2 个方块,但是当我尝试使用其他方块时,它会继续打印 1 invalid diagonal
.
更多详情见评论讨论:
public static boolean checkDiagonals(int[][] array, int magicConstant){
int total1 = 0;
int total2 = 0;
int wrong = 0;
for(int i = 0; i < array.length; i++){
total1= total1 + array[i][i];
total2 = total2 + array[array.length - i-1][array.length - i-1];
}
if(total1!=magicConstant){
wrong++;
}
if(total2!=magicConstant){
wrong++;
}
System.out.println("There were " + wrong + " invalid diagnals.");
return wrong == 0;
}