【问题标题】:CS50 Filter grayscale check50CS50 滤镜灰度检查50
【发布时间】:2020-06-09 13:19:30
【问题描述】:

灰度代码似乎在以整数为平均值的程序中运行良好。但会给出复杂平均值的错误,其中结果与预期代码仅相差 1。

// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    double avgcolor;
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            avgcolor = (image[i][j].rgbtRed + image[i][j].rgbtBlue + image[i][j].rgbtGreen) / 3;
            image[i][j].rgbtRed = image[i][j].rgbtBlue = image[i][j].rgbtGreen = round(avgcolor);
         }
    }
    return;
}

错误信息

:( grayscale correctly filters single pixel without whole number average
Cause
expected "28 28 28\n", not "27 27 27\n"
Log
testing with pixel (27, 28, 28)
running ./testing 0 1...
checking for output "28 28 28\n"...

Expected Output:
28 28 28
Actual Output:
27 27 27

我在另外两种情况下遇到此类错误。这可能是轮函数的一个小问题。代码查了好几遍,还是找不到错误原因。

【问题讨论】:

    标签: cs50


    【解决方案1】:

    您将两个整数相除,因此 C 将计算您的平均值(可能不是整数),然后删除小数点后的数字。因为image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtRed 将始终是一个整数,所以将此整数值除以另一个整数 3 将返回另一个整数,而不考虑任何小数点。换句话说,如果image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtRed/3 = 27.66avgcolor 将等于27。对此的解决方案是将颜色值除以3.0,一个浮点数。整数除以浮点数可以返回浮点数,但不能返回整数除以整数。

    试试这段代码,用 3.0 进行浮点除法运算:

    // Convert image to grayscale
    void grayscale(int height, int width, RGBTRIPLE image[height][width])
    {
        double avgcolor;
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                avgcolor = (image[i][j].rgbtRed + image[i][j].rgbtBlue + image[i][j].rgbtGreen) / 3.0;
                image[i][j].rgbtRed = image[i][j].rgbtBlue = image[i][j].rgbtGreen = round(avgcolor);
             }
        }
        return;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 1970-01-01
      • 2016-01-06
      • 2014-02-11
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多