[英]Problems with [ ][ ] and if-statement
我的程序中有錯誤,我將在下面說明:
int[][]image =
{
{0,0,2,0,0,0,0,0,0,0,0,0},
{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},
{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,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,0,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[][]
注意圖像[] []。 它是由一系列數字組成的2D數組。 它下面的代碼初始化一個名為smooth [] []的新2D數組,它與image [] []相同。
我將smooth [] []中的每個元素替換為數組中包圍它的八個元素(加上元素本身)的數字平均值。 這個,我做了。
但是,請注意image [] []中位於數組邊緣的元素。 這些元素位於第0行和第0列。這些邊元素中的任何一個,我想在smooth [] []中保持相同。 我嘗試使用if語句執行此操作,但它不起作用。 我該如何工作?
// compute the smoothed value of non-edge locations insmooth[][]
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) {
smooth[r][c] = image[r][c];
}
if (r >= 1 && c >= 1) {
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
}
}
}
菲爾表示你的條件應該檢查行== 0或col == 0
//compute the smoothed value of non-edge locations insmooth[][]
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) {
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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.