CS50 滤镜灰度检查50
CS50 Filter grayscale check50
灰度代码似乎 运行 适合以整数为平均值的程序。但是给出复杂平均值的错误,其中结果与预期代码仅相差 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
我在另外两个案例中遇到了这样的错误。这可能是 round 函数的一个小问题。代码看了好几遍还是没找到错误原因
你要除两个整数,所以 C 会计算你的平均值,它可能不是整数,然后去掉小数点后的数。因为 image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtRed
将始终是一个整数,所以将该整数值除以另一个整数 3 将 return 另一个整数,无论小数点是多少。换句话说,如果 image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtRed/3 = 27.66
那么 avgcolor
将等于 27。解决这个问题的方法是将颜色值除以 3.0,一个浮点数。整数除以浮点数可以是 return 浮点数,但不能是整数除以整数。
试试这个代码,你用 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;
}
灰度代码似乎 运行 适合以整数为平均值的程序。但是给出复杂平均值的错误,其中结果与预期代码仅相差 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
我在另外两个案例中遇到了这样的错误。这可能是 round 函数的一个小问题。代码看了好几遍还是没找到错误原因
你要除两个整数,所以 C 会计算你的平均值,它可能不是整数,然后去掉小数点后的数。因为 image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtRed
将始终是一个整数,所以将该整数值除以另一个整数 3 将 return 另一个整数,无论小数点是多少。换句话说,如果 image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtRed/3 = 27.66
那么 avgcolor
将等于 27。解决这个问题的方法是将颜色值除以 3.0,一个浮点数。整数除以浮点数可以是 return 浮点数,但不能是整数除以整数。
试试这个代码,你用 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;
}