首页 > 解决方案 > 在 CS50 Pset4 反射中找不到什么问题?

问题描述

我已经为反射编写了这段代码,当我使用 check50 时,我得到了以下信息:

:( reflect correctly filters 1x2 image
    expected "0 0 255\n255 0...", not "0 0 255\n0 0 2..."

:( reflect correctly filters 1x3 image
    expected "0 0 255\n0 255...", not "0 0 255\n0 255..."

:) reflect correctly filters image that is its own mirror image

:( reflect correctly filters 3x3 image
    expected "70 80 90\n40 5...", not "70 80 90\n40 5..."

:( reflect correctly filters 4x4 image
    expected "100 110 120\n7...", not "100 110 120\n7..."

然而这些数字似乎是一样的......

这是我的反射功能:

/ Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    //Cycle through rows
    for (int i = 0; i < height; i++)
    {   //Cycle through columns
        for (int j = 0; j < width; j++)
        {   //Swap the current cell with oppsite cell.
            image[i][j].rgbtRed = image[i][width - j - 1].rgbtRed;
            image[i][j].rgbtBlue = image[i][width - j - 1].rgbtBlue;
            image[i][j].rgbtGreen = image[i][width - j - 1].rgbtGreen;
        }    
    }
    
    return;
} 

标签: ccs50

解决方案


首先,我想指出 check50 只显示了一个很小的像素子集;仅仅因为您正确反映了前 2-3 个像素,并不意味着所有这些像素都是正确的。

也就是说,这里有三个改进代码的建议:

  1. 您的目标是将图像上的一半移动到另一半。因此,您不会想要遍历所有列,因为正如 0x5453 所说,这会导致您只反射两次,从而使图像保持原样,但只有一半。您可以通过设置j < round(width / 2.0)第二个 for 循环来做到这一点。
  2. 记得大卫马兰的讲座中,你需要一个临时杯子来切换两个杯子的内容。所以你应该将一个临时变量设置为原始像素,然后将原始像素设置为另一侧的一个,然后将另一侧的一个设置为临时变量。这会将原始像素与另一侧的像素切换;即反射。
  3. 由于您只是在切换像素,因此您无需为单个颜色而烦恼;你可以只处理image[i][j]而不是image[i][j].rgbtRed和所有其他颜色。在涉及颜色失真的其他部分中,您需要处理颜色。

推荐阅读