我设置了一个 10 x 10 的二维数组,每个槽对应其各自的位置。我正在尝试将第 3、5 和 7 列中的所有数字添加到 cTotal 中,并将第 2、4 和 6 行中的所有数字添加到 rTotal 中。我的编码看起来不错,但我似乎无法让它工作。有什么想法吗?
public static void arrayMath()
{
int cTotal = 0;
int rTotal = 0;
//int tDiffValue = (rTotal - cTotal);
int twodimarr[][] = new int[10][10];
int row = 10;
int col = 10;
int x = 0;
int y = 0;
for(x = 0; x < row; x++)
{
for(y = 0; y < col; y++)
{
twodimarr[x][y] = x*y;
}
}
for(x = 0; x < row; x++)
{
for(y = 0; y < col; y++)
{
if( (x+y) < col )
{
//System.out.print( " " );
}
//System.out.print(" " + (twodimarr[x][y]));
}
//System.out.println();
}
for(x = 0; x < twodimarr.length; x++) //Problems start down here.
{
for( y= 0; y<twodimarr.length; y++)
{
if(y == 2 || y == 4 || y == 6)
{
rTotal = ((rTotal + twodimarr[x][y]));
}
}
}
System.out.println("rTotal is " + rTotal + ".");
for(x = 0; x < twodimarr.length; x++)
{
for(y = 0; y < twodimarr.length; y++)
{
if(x == 3 || x == 5 || x == 7)
{
cTotal = ((cTotal + twodimarr[x][y]));
}
}
}
System.out.print("cTotal is " + cTotal + ".");
}
最佳答案
x==3 不是第三列,而是第四列(0,1,2,3)。这意味着它是 3*0、3*1 等列,在这种情况下 675/540 数字是正确的。
关于java - 在 10x10 二维数组中完成的数学运算无法正确计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15744416/