在2D阵列中找到最大的2x2平均值

时间:2015-10-31 19:35:19

标签: c++ arrays loops matrix average

我试图在矩阵中找到最大的2x2平均值。我找到了一个与similar problem共享的人,然而,他们的解决方案不起作用。

以下是我的代码:

//Part B
        //Finding deepest 2x2 area
            int rowX, colX, ac1Row, ac1Col, ac2Row, ac2Col, ac3Row, ac3Col, ac4Row, ac4Col;
            float largestArea = 0;
            for(rowX = 0; rowX < dataRow - 1; rowX++){
                for(colX = 0; colX < dataCol - 1; colX++){

                    float area = (oceanData[rowX][colX] + oceanData[rowX][colX + 1] + oceanData[rowX + 1][colX] + oceanData[rowX + 1][colX + 1]) / 4;
                    if(largestArea < area){
                        largestArea = area;
                        int ac1Row = rowX; int ac1Col = colX;
                        int ac2Row = rowX; int ac2Col = colX + 1;
                        int ac3Row = rowX + 1; int ac3Col = colX;
                        int ac4Row = rowX + 1; int ac4Col = colX + 1;
                    }
                }
            }
            //Display results
            cout << endl << "The deepest 2x2 area is: " << largestArea << " m" << endl;
            cout << endl << "The coordinates are: (" << ac1Row << "," << ac1Col << ")" << " " << "(" << ac2Row << "," << ac2Col << ")";
            cout << "(" << ac3Row << "," << ac3Col << ")" << "(" << ac4Row << "," << ac4Col << ")" << endl;

我使用.txt文件,我的数据是6乘6(数据存储在oceanData中,大小存储在dataRow和dataCol中)我的输出给出了平均值(据说),但是,当我尝试输出坐标我得到奇怪的数字: 离。

The coordinates are: (4356788,0),(0,0),(0,0),(8,0)

有人知道我的问题在哪里吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

您正在重新定义每个循环上的变量:

   int ac1Row = rowX; int ac1Col = colX;

但是你甚至不需要所有8个变量,你只能保存一个角落的坐标并计算其他角落。

考虑一下

       int acRow, acCol;
        float largestArea = 0;
        for(int rowX = 0; rowX < dataRow - 1; rowX++){
            for(int colX = 0; colX < dataCol - 1; colX++){

                float area = (oceanData[rowX][colX] + oceanData[rowX][colX + 1] + oceanData[rowX + 1][colX] + oceanData[rowX + 1][colX + 1]) / 4;
                if(largestArea < area){
                    largestArea = area;
                    acRow = rowX; 
                    acCol = colX;                        
                }
            }
        }
 cout << endl << "The deepest 2x2 area is: " << largestArea << " m" << endl;
 cout << endl << "The coordinates are: (" << acRow << "," << acCol << ")" << " " << "(" << acRow  << "," << acCol + 1  << ")";
 cout << "(" << acRow + 1 << "," << acCol << ")" << "(" << acRow + 1 << "," << acCol + 1 << ")" << endl;