CS50 pset 4模糊过滤器-与预期输出有1个值偏差

mkshixfv  于 2023-05-16  发布在  其他
关注(0)|答案(1)|浏览(98)

我正在处理CS50的模糊滤镜分配。看来我的模糊值计算代码有问题。
这是我的代码:

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    // Create a copy of the original image
    RGBTRIPLE tmp[height][width];
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            tmp[i][j] = image[i][j];
        }
    }

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {

            // predefine all the needed variables
            int Sum_Red = 0;
            int Sum_Green = 0;
            int Sum_Blue = 0;
            int COUNT = 0;

            //check the boundary and iterating the funtion within three blocks
            for (int k = -1; k < 2; k++)
            {
                for (int l = -1; l < 2; l++)
                {
                    int new_i = i + k;
                    int new_j = j + l;

                    // Nine block cases
                    if (new_i >= 0 && new_i < height && new_j >= 0 && new_j < width)
                    {
                        Sum_Red += tmp[new_i][new_j].rgbtRed;
                        Sum_Green += tmp[new_i][new_j].rgbtGreen;
                        Sum_Blue += tmp[new_i][new_j].rgbtBlue;
                        COUNT++;
                    }
                }
            }
            image[i][j].rgbtRed = round(Sum_Red / COUNT);
            image[i][j].rgbtGreen = round(Sum_Green / COUNT);
            image[i][j].rgbtBlue = round(Sum_Blue / COUNT);
        }
    }
    return;
}

输出如下所示:enter image description here
似乎有些数值稍微超出了预期。
我看到别人的代码是这样的,我实现了int k和l以避免边界:

for (int r = -1; r < 2; r++)
            {
                for (int c = -1; c < 2; c++)
                {
                    if (i + r < 0 || i + r > height - 1)
                    {
                        continue;
                    }

                    if (j + c < 0 || j + c > width - 1)
                    {
                        continue;
                    }

                    sumBlue += image[i + r][j + c].rgbtBlue;
                    sumGreen += image[i + r][j + c].rgbtGreen;
                    sumRed += image[i + r][j + c].rgbtRed;
                    counter++;
                }
            }

这段代码和我的代码在数学上有什么区别?我做了计算,直觉上它们是一样的,然而,输出是不一样的。使用CS50检查他人代码是否输出正确。

eqfvzcg8

eqfvzcg81#

我知道问题的根源……我应该定义所有的变量float而不是int,以避免意外的 Backbone.js 关闭。

float Sum_Red = 0;
    float Sum_Green = 0;
    float Sum_Blue = 0;
    float COUNT = 0;

就像这样

相关问题