为什么我的条件(IF 语句)return 为假?

Why do my conditions (IF statements) return false?

我正在尝试解决 CS50x 课程中 PSET4 filter(less) 中的模糊功能。这是问题所在:


模糊

有多种方法可以创建模糊或柔化图像的效果。对于这个问题,我们将使用“框模糊”,它的工作原理是获取每个像素,并针对每个颜色值,通过平均相邻像素的颜色值为其赋予一个新值。

每个像素的新值将是原始像素 1 行和 1 列内所有像素值的平均值(形成 3x3 框)。例如,像素 6 的每个颜色值将通过对像素 1、2、3、5、6、7、9、10 和 11 的原始颜色值进行平均来获得(请注意,像素 6 本身包含在平均的)。同样,像素 11 的颜色值将通过对像素 6、7、8、10、11、12、14、15 和 16 的颜色值进行平均来获得。

对于沿着边缘或角落的像素,例如像素 15,我们仍然会寻找 1 行和 1 列内的所有像素:在这种情况下,像素 10、11、12、14、15 和 16。


这是我目前写的代码:

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            int red = image[i][j].rgbtRed;
            float count = 0.0;
            int blurRed = 0;

            for (int k = 0; (k <= i + 1) && (k < height); k++)
            {
                for (int l = 0; (l <= j + 1) && (l < width); l++)
                {
                    int sumRed = image[k][l].rgbtRed;

                    if ((k - 1 >= 0) && (k + 1 < height))
                    //these if statements should ensure that the following action is only carried out IF the k/l indices do not exceed height and width
                    {
                        sumRed += image[k - 1][l].rgbtRed;
                        count++;
                    }

                    if ((l - 1 >= 0) && (l + 1 < width))
                    {
                        sumRed += image[k][l - 1].rgbtRed;
                        count++;
                    }
                    blurRed = roundf(sumRed / count);
                }
            }          
            red = blurRed;
        }
    }
}

虽然我不确定我的解决方案是否走在正确的轨道上。当我 运行 代码时,我收到此错误消息:

helpers.c:139:45: runtime error: division by zero helpers.c:139:32: runtime error: inf is outside the range of representable values of type 'int'

所以我想知道为什么我的计数器总是保持在 0。

期待一些帮助和答案!

在第一次迭代中,当k = 0时,条件k - 1 >= 0将计算为假,0 - 1不是>= 0,[=15也是如此=],结果 count 将是 0 并执行除以 0

此外,count 应该是一个整数值,最好是无符号的。为避免此更改导致的整数除法舍入问题,您可以稍后将 sumRedcount 转换为 float:

blurRed = roundf((float)sumRed/count);

或者简单地将 sumRead 声明为 float 而不是 int