簡體   English   中英

2D陣列從左到右,然后從右到左輸出。 似乎無法獲得正確的元素

[英]2D Array outputting from left to right, then right to left. Can't seem to get the correct element

我必須在偶數行上從左到右輸出我的2D數組,在奇數行上從右到左輸出2D數組。 我已經做到了,那不是問題。 問題是當我嘗試訪問2D數組中的元素時,我感到非常困惑,因為現在奇數行被反轉了。

這是我當前的輸出,輸出從左到右然后從右到左:

0.5       0.62      0.35      0.6       0.5       
0.13      0.25      0.25      0.62      0.45      
0.65      0.85      0.2       0.2       0.8 

以下是輸出,未對輸出進行任何更改:

0.5       0.62      0.35      0.6       0.5       
0.45      0.62      0.25      0.25      0.13
0.65      0.85      0.2       0.2       0.8 

我需要獲取每個2 X 2的平均值,然后找出哪個是最弱的。 我已經做到了,但是數學似乎無法解決問題,我認為這是因為奇數行上的元素被顛倒了。

這是我當前發現最弱的輸出:

0.5
0.45999999999999996
0.3625
0.3625
0.3625
0.3625
0.22499999999999998
0.22499999999999998
Weakest begins at (1, 2) with an average strength of 0.22499999999999998

正確的輸出應該具有0.3175的平均強度:

Weakest begins at (1, 2) with an average strength of 0.3175

最后,這是我的代碼,用於使每個奇數行從右向左輸出:

int k = 0;
        cd = new double[3][5];
        for(int i = 0; i<cd.length;i++)
            for(int j=0; j<cd[i].length;j++,k++)
                 cd[i][j]=gridArr[k];
        for(int i = 0; i < cd.length; i++){
            if(i%2==0)
                for(int j = 0; j < cd[i].length; j++)
                    System.out.print(String.format("%-10s" ,cd[i][j]));
            else
                for(int j = cd[i].length -1; j >= 0; j--)
                    System.out.print(String.format("%-10s" ,cd[i][j]));
            System.out.println();
        }

這是找到最弱的2 X 2的代碼:

double weakest = getAverage(0, 0, 0, 0);
    int weakestRow = 0;
    int weakestCol = 0;
    for(int row = 0; row < cd.length-1; row++){
        for(int col = 0; col < cd[0].length-1;col++){
            if(weakest > getAverage(row, row+1, col, col+1)) {
                weakest = getAverage(row, row+1, col, col+1);
                weakestRow = row;
                weakestCol = col;
            } System.out.println(weakest);
        }
    }
    System.out.println("\nWeakest begins at "
            +"("+weakestRow+", "+weakestCol+") with an average strength of "
            +weakest);
}

有任何想法嗎? 我已經看了好幾個小時了,無法把頭纏住……

編輯: getAverage是:

    double first = cd[startRow][startCol];
    double second = cd[endRow][startCol];
    double third = cd[startRow][endCol];
    double fourth = cd[endRow][endCol];
    return (first+second+third+fourth)/4;

這是因為您的程序是在原始數組上找到平方的平均值,而不是在您將奇數行的順序顛倒的那個平均值。

顯示陣列無效。

您應該做的是在已反轉奇數行的數組上調用getWeakest方法。

   oddRowReversedArray = new double[3][5];
   for(int i = 0; i < cd.length; i++){
        if(i%2==0)
            oddRowReversedArray[i] = cd[i]
        else
            for(int j = cd[i].length -1; j >= 0; j--)
                oddRowReversedArray[i][j] = cd[i][cd.length -1 -j]
    }

然后調用此數組的getWeakest。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM