gpt4 book ai didi

c++ - 区域中的最大元素

转载 作者:行者123 更新时间:2023-11-30 02:48:47 25 4
gpt4 key购买 nike

我想将数组中某个元素的值与相邻元素 (3x3) 进行比较,并找出最大值(图)。我下面的代码似乎不起作用。哪一部分出了问题? enter image description here

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: enter image description here

最佳答案

以下内容可能会有所帮助:( 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;
}
}
}
}

关于c++ - 区域中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com