CS50滤镜灰度检查

时间:2020-06-09 13:19:30

标签: cs50

对于具有整数平均值的程序,灰度代码似乎运行良好。但是会给平均值带来错误,结果与预期的代码仅相差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

在另外两种情况下,我也会收到此类错误。舍入功能可能是一个小问题。我已经遍历了几次代码,但仍然找不到错误的原因。

1 个答案:

答案 0 :(得分: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.66等于avgcolor,则等于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;
}