// Detect edges
void edges(int height, int width, RGBTRIPLE image[height][width])
{
// Copying
RGBTRIPLE copy[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
copy[i][j] = image[i][j];
}
}
int Gx[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
int Gy[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int GxsumRed = 0;
int GxsumGreen = 0;
int GxsumBlue = 0;
int GysumRed = 0;
int GysumGreen = 0;
int GysumBlue = 0;
// Forming 3x3 grid
int m = 0; // For Gx and Gy
for (int k = i - 1; k < i + 2; k++)
{
if (k < 0)
{
continue;
}
// if k > height then break
if (k >= height)
{
break;
}
int n = 0; // For Gx and Gy
for (int l = j - 1; l < j + 2; l++)
{
if (l < 0)
{
continue;
}
if (l >= width)
{
break;
}
GxsumRed += Gx[m][n] * copy[k][l].rgbtRed;
GxsumGreen += Gx[m][n] * copy[k][l].rgbtGreen;
GxsumBlue += Gx[m][n] * copy[k][l].rgbtBlue;
GysumRed += Gy[m][n] * copy[k][l].rgbtRed;
GysumGreen += Gy[m][n] * copy[k][l].rgbtGreen;
GysumBlue += Gy[m][n] * copy[k][l].rgbtBlue;
n++;
}
m++;
}
int newRed = round(sqrt((GxsumRed * GxsumRed) + (GysumRed * GysumRed)));
int newGreen = round(sqrt((GxsumGreen * GxsumGreen) + (GysumGreen * GysumGreen)));
int newBlue = round(sqrt((GxsumBlue * GxsumBlue) + (GysumBlue * GysumBlue)));
// Caping to 255
if (newRed > 255)
{
newRed = 255;
}
if (newGreen > 255)
{
newGreen = 255;
}
if (newBlue > 255)
{
newBlue = 255;
}
image[i][j].rgbtRed = newRed;
image[i][j].rgbtGreen = newGreen;
image[i][j].rgbtBlue = newBlue;
}
}
return;
}
此 CS50 问题集 4. 筛选更多问题。除了边缘功能之外,一切都很好。 ChatGPT 说我的代码是正确的,但 check50 说它不正确,为什么? 我做错了什么?
请问有人可以告诉我吗?拜托拜托?
这就是所有细节。
问题是您在循环体末尾递增
n
和 m
,但是当 k < 0
或 l < 0
分别为 true 并且对 continue
语句求值时,此增量将被绕过。
您应该避免使用
continue
语句,或者将增量移至 for
语句的第三个子句。
如果
k >= height
或 l >= width
提前退出循环是一种优化,它会破坏代码的对称性,并使编译器更难以展开或并行化循环。即使对于中等大小的图像,这种优化也是微不足道的。建议优先考虑代码的可读性和规律性,而不是过早的优化。
这是内部循环的修改版本:
// Forming 3x3 grid
for (int m = 0; m < 3; m++)
{
int k = i - 1 + m;
if (k >= 0 && k < height)
{
for (int n = 0; n < 3; n++)
{
int l = j - 1 + n;
if (l >= 0 && l < width)
{
GxsumRed += Gx[m][n] * copy[k][l].rgbtRed;
GxsumGreen += Gx[m][n] * copy[k][l].rgbtGreen;
GxsumBlue += Gx[m][n] * copy[k][l].rgbtBlue;
GysumRed += Gy[m][n] * copy[k][l].rgbtRed;
GysumGreen += Gy[m][n] * copy[k][l].rgbtGreen;
GysumBlue += Gy[m][n] * copy[k][l].rgbtBlue;
}
}
}
}