gpt4 book ai didi

java - [ ][ ] 和 if 语句在代码中不起作用

转载 作者:行者123 更新时间:2023-12-01 18:14:48 26 4
gpt4 key购买 nike

我在下面的代码中遇到一些关于 if 语句和可能的 2D 数组的问题,我在下面说明:

int[][]image =
{
{0,0,2,0,0,0,0,0,0,0,0,2},
{0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,5,5,5,5,5,5,5,5,0,0},
{0,0,5,5,5,5,5,5,5,5,0,0},
{0,0,5,5,5,5,5,5,5,5,0,0},
{2,0,5,5,5,5,5,5,5,5,0,2},
{0,0,5,5,5,5,5,5,5,5,0,0},
{0,0,5,5,5,5,5,5,5,5,0,0},
{0,0,5,5,5,5,5,5,5,5,0,0},
{0,0,5,5,5,5,5,5,5,5,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,2,0,0,0,0,0,0,0}//assume this rectangular image
};

int[][]smooth = new int[image.length][image[0].length]; //new array equal to image[][]

注意图片[][]。它是由一系列数字组成的二维数组。在它下面,我初始化了一个相同的数组:smooth[][]。 smooth[][] 的每个元素都替换为 8 个边界元素加上其自身的数值平均值。

smooth[][] 中的边缘元素(数组外边界上的元素)不应更改。

我尝试使用 if 语句来做到这一点,但只成功了一半。上边框和左边框上的数字不会改变(r == 0 || c == 0),但下边框或右边框上的任何数字都会更改为平均值。

    //compute the smoothed value of non-edge locations in smooth[][]

for(int r=0; r<image.length-1; r++)
{// x-coordinate of element

for(int c=0; c<image[r].length-1; c++)
{ //y-coordinate of element

int sum1 = 0;//sum of each element's 8 bordering elements and itself



if(r == 0 || c == 0 || r == (image[c].length) || c == (image[r].length))
smooth[r][c] = image[r][c];

else
{

sum1 = image[r-1][c-1] + image[r-1][c] + image[r-1][c+1]
+ image[r][c-1] + image[r][c] + image[r][c+1] +image[r+1][c-1]
+ image[r+1][c] + image[r+1][c+1];

smooth[r][c]= sum1 / 9; //average of considered elements becomes new elements

最佳答案

您太早停止处理,使您的 if 语句无法捕获右侧和底部边框情况。您的 for 循环条件:

for(int r=0; r<image.length-1; r++)     
{// x-coordinate of element

for(int c=0; c<image[r].length-1; c++)
{ //y-coordinate of element

在到达右列或底行之前停止处理。默认值 0 恰好与由于全部为零而存在的平均值相匹配。

通过更改 for 循环条件以包含右侧和底部边界情况,让您的 if 语句捕获边界情况 - 不要减去 1 从长度开始。

for(int r=0; r<image.length; r++)     
{// x-coordinate of element

for(int c=0; c<image[r].length; c++)
{ //y-coordinate of element

但是您必须正确测试“在右侧”和“在底部”条件。将此处数组的长度减一。

if(r == 0 || c == 0 || r == (image[c].length - 1) || c == (image[r].length - 1))
smooth[r][c] = image[r][c];

关于java - [ ][ ] 和 if 语句在代码中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311510/

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