You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50模糊函数输出错误求助:全部测试用例未通过

CS50 Blur函数实现错误排查

测试用例失败信息

:( blur correctly filters middle pixel
expected "127 140 149\n", not "143 158 168\n"
:( blur correctly filters pixel on edge
expected "80 95 105\n", not "96 114 126\n"
:( blur correctly filters pixel in corner
expected "70 85 95\n", not "93 113 127\n"
:( blur correctly filters 3x3 image
expected "70 85 95\n80 9...", not "93 113 127\n96..."
:( blur correctly filters 4x4 image
expected "70 85 95\n80 9...", not "93 113 127\n96..."

实现代码

void blur(int height, int width, RGBTRIPLE image[height][width])
{
    RGBTRIPLE copy[height][width];

    int offsetx[] = {0, 1, 1, 1, 0, -1, -1, -1};
    int offsety[] = {-1, -1, 0, 1, 1, 1, 0, -1};

    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            int sum_Red = 0;
            int sum_Green = 0;
            int sum_Blue = 0;
            int counter = 0;

            for(int i = 0; i < 9; i++)
            {
                int r = row + offsetx[i];
                int c = col + offsety[i];


                 if (r >= 0 && r < height && c >= 0 && c < width)
                 {
                    sum_Red += image[r][c].rgbtRed;
                    sum_Green += image[r][c].rgbtGreen;
                    sum_Blue += image[r][c].rgbtBlue;
                    counter++;

                 }
            }

            copy[row][col].rgbtRed = round(sum_Red / (double)counter);
            copy[row][col].rgbtGreen = round(sum_Green / (double)counter);
            copy[row][col].rgbtBlue = round(sum_Blue / (double)counter);
         }
    }

    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            image[row][col] = copy[row][col];
        }
    }
    return;
}

错误原因与修正

  • 核心问题:偏移数组遗漏当前像素
    你定义的offsetx和offsety仅包含8组偏移值,但循环执行了9次。当前像素(row, col)对应的偏移(0, 0)未被加入数组,导致第9次循环时访问了数组越界的垃圾值,错误地引入了额外像素的颜色值,最终计算出的总和偏大,模糊结果比预期更亮,与测试用例的输出差异完全吻合。

  • 修正方案
    给偏移数组补充(0, 0)的偏移值,让数组包含完整的9组方向(当前像素+周围8个邻居):

    // 修正后的偏移数组,包含当前像素(0,0)
    int offsetx[] = {-1, -1, -1, 0, 0, 0, 1, 1, 1};
    int offsety[] = {-1, 0, 1, -1, 0, 1, -1, 0, 1};
    

    这样每个像素计算时都会包含自身,角落像素的有效邻居数为3,边缘非角落为5,中间像素为9,完全符合模糊算法的计算逻辑,计算出的平均值会与测试用例预期一致。

内容的提问来源于stack exchange,提问作者Anastasiia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:45:26