我想比较数组中元素的值与相邻元素(3x3)并找到最大值(数字)。我的代码似乎不起作用。哪部分出了问题?
int data[10][10] = {};
int dataMax[10][10] = {};
int r_size = 3; // Size of region to compare
int h = floor(r_size/2);
for(int i = h; i < ( 10 - h ) ; i++){
for(int j = h; j < ( 10 - h ); j++){
int max = 0;
for( int ii = i - h; ii < ( i + h ); ii++ ){
for( int jj = j - h; jj < ( j + h ); jj++ ){
if( data[ii][jj] > max ){
max = data[ii][jj];
}else{
dataMax[ii][jj] = 0;
}
}
}
dataMax[ii][jj] = data[ii][jj];
}
}
[根据答案编辑]
int data[10][10] =
{{0,0,3,0,1,0,0,0,0,1},
{0,0,0,2,0,0,0,0,0,0},
{0,0,0,0,0,0,1,1,0,0},
{0,0,0,0,0,0,0,3,0,0},
{0,4,2,0,0,0,0,0,0,0},
{0,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,8,1,1,0,0},
{0,0,0,0,3,6,0,0,2,0},
{2,0,0,0,0,0,0,0,0,0}};
int dataMax[10][10] = {};
int r_size = 3; // Size of region to compare
int h = floor(r_size/2.0);
for(int i = h; i < ( 10 - h ) ; i++){ //**** correction ****
for(int j = h; j < ( 10 - h ); j++){ //**** correction ****
int max = 0;
int max_x = 0; //**** correction ****
int max_y = 0;
for( int ii = i - h; ii <= ( i + h ); ii++ ){ //**** correction ****
for( int jj = j - h; jj <= ( j + h ); jj++ ){ //**** correction ****
if( data[ii][jj] > max ){
max = data[ii][jj];
max_x = ii; //**** correction ****
max_y = jj;
}else{
// dataMax[ii][jj] = 0;
}
}
}
dataMax[max_x][max_y] = max; //**** correction ****
}
}
我希望得到以下dataMax:
答案 0 :(得分:1)
int h = floor(r_size/2);
h现在是1.
和
for( int ii = i - h; ii < ( i + h ); ii++ ){
在i-1
到i+1
之间进行迭代,总共进行两次迭代。您应该将其更改为<=
三次迭代。
答案 1 :(得分:1)
此刻,你写的地方
dataMax[ii][jj] = data[ii][jj];
变量ii
以及jj
不再声明。此外:如果您正在寻找,那么您不会将max
值存储在任何位置,这应该会发生。
编辑:在您的修改中发现了另一个错误:尝试设置dataMax[max_x][max_y] = max;
,因为您混淆了行和列data[max_x][max_y]
应该是data[max_y][max_x]
到目前为止可以看到。
但无论如何,既然你要存储最大值,为什么不使用它呢?
答案 2 :(得分:1)
以下可能有所帮助:(https://ideone.com/xJXzp8)
int getMax(int minx, int maxx, int miny, int maxy)
{
minx = std::max(minx, 0);
maxx = std::min(maxx, 10);
miny = std::max(miny, 0);
maxy = std::min(maxy, 10);
int res = data[minx][miny];
for (int x = minx; x != maxx; ++x) {
for (int y = miny; y != maxy; ++y) {
res = std::max(res, data[x][y]);
}
}
return res;
}
void compute()
{
const int h = 3; // Size of region to compare
for (int x = 0; x != 10; ++x) {
for (int y = 0; y != 10; ++y) {
dataMax[x][y] = getMax(x - h / 2, x + h - h / 2,
y - h / 2, y + h - h / 2);
}
}
}
void filter()
{
for (int x = 0; x != 10; ++x) {
for (int y = 0; y != 10; ++y) {
if (dataMax[x][y] != data[x][y]) {
dataMax[x][y] = 0;
}
}
}
}