[英]Swapping rows of double 2d array java
我試圖用Java編寫一個方法,使我可以交換double類型的2d數組的行。 當我在2d的int數組上使用我的代碼時,它可以完美地工作,但是當應用於double時,它不能工作。 我是否缺少有關雙數據類型的基本知識? 非常感謝任何見解。
// swapRows
// double[][] Integer -> double[][]
public static double[][] swapRows(double[][] a, int i)
{
double[] temp = a[i];
for(; i < a.length - 1; i++)
a[i] = a[i+1];
a[a.length - 1] = temp;
return a;
}
//版本2,帶有新的2d數組
public static double[][] swapRows(double[][] a, int i)
{
double[][] b = new double[a.length][a[0].length];
double[] temp = a[i];
for(int k = 0; k < i;k++)
b[k] = a[k];
for(; i < a.length - 1; i++)
b[i] = a[i+1];
b[b.length - 1] = temp;
return b;
}
//請注意,這些行不僅交換,還將指定的行i發送到數組的底部,並且每隔一行將//移至2d數組:
{ {3, 5, 6},
{2, 1, 1},
{9, 0, 4} }
//我希望當i = 0時,該方法返回2d數組:
{ {2, 1, 1},
{9, 0, 4},
{3, 5, 6} }
//但是我得到:
{ {0.0, -29.999996, -38.571428},
{18.999997, 0.0, 0.999999},
{18.0, 29.999996, 36.0} }
//當我使用int而不是double時,得到了期望的數組
因為代碼是正確的恕我直言,所以2D數組必須損壞( 不太可能 ,兩行中都存在相同的double[]
行對象),或者更可能是您更改了傳遞的數組並返回了它,這可能表示一些錯誤。處理結果。
double[][] a = ...
double[][] b = swapRows(a, i);
// a == b
一個創建副本的版本已更改:
public static double[][] swapRows(double[][] a, int i) {
double[][] result = new double[a.length][];
for (int j = 0; j < a.lnength; ++j) {
result[j] = Arrays.copyOf(a[j], a[j].length);
}
double[] temp = result[i];
for(; i < result.length - 1; i++) {
result[i] = result[i+1];
}
result[result.length - 1] = temp;
return result;
}
double[][] a = { { 1.0, 2.0 }, { 3.0, 4.0 } };
double[][] b = swapRows(a, 0);
assert b[0][0] == 3.0 && b[0][1] == 4.0 && b[1][0] == 1.0 && b[1][1] == 2.0;
System.out.println("result = " + Arrays.deepToString(result));
我發現了問題。 在主函數中,我還有其他測試行正在修改數組的值,然后再將其傳遞給swapRows方法。 感謝您的協助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.