cs50 weak 4 reflect problem,输出中每列的第一行始终为零的问题

g6baxovj  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(87)

当运行cheak50时,我遇到一些错误。当我在图像上测试代码时,它工作正常,并反映了图像。问题是每列的第一行总是包含零,尽管它应该接受值。
下面的测试使用3x3图像

Cause
expected "255 0 0\n255 0...", not "0 0 0\n255 0 0..."
Log
testing with sample 3x3 image
first row: (255, 0, 0), (255, 0, 0), (255, 0, 0)
second row: (0, 255, 0), (0, 255, 0), (0, 0, 255)
third row: (0, 0, 255), (0, 0, 255), (0, 0, 255)
running ./testing 2 2...
checking for output "255 0 0\n255 0 0\n255 0 0\n0 255 0\n0 255 0\n0 255 0\n0 0 255\n0 0 255\n0 0 255\n"...

预期输出:

255 0 0
255 0 0
255 0 0
0 255 0
0 255 0
0 255 0
0 0 255
0 0 255
0 0 255

实际输出:

0 0 0
255 0 0
255 0 0
0 0 0
0 255 0
0 255 0
0 0 0
0 0 255
0 0 255

代码

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    //this is where the reflected image gonna be
    RGBTRIPLE reflected[height][width];
    for (int h = 0 ; h < height ; h++)
    {
        for (int w = 1 ; w < width ; w++)
        {
            reflected[h][w] = image[h][width-1 - w];
        }
    }
    //copying from the reflected to the image
    for (int h = 0 ; h < height ; h++)
    {
        for (int w = 0 ; w < width ; w++)
        {
           image[h][w] = reflected[h][w];
        }
    }
    return;
}

我认为这与for循环有关。

am46iovg

am46iovg1#

正如注解部分所指出的,你必须在下面一行中修复w初始化器:

for (int w = 1 ; w < width ; w++)

收件人:

for (int w = 0 ; w < width ; w++)

我认为这就足够了:

$ cat main.c
#include <stdio.h>

void reflect(int height, int width, int image[height][width])
{
    //this is where the reflected image gonna be
    int reflected[height][width];
    for (int h = 0 ; h < height ; h++)
    {
        for (int w = 0 ; w < width ; w++)
        {
            reflected[h][w] = image[h][width -1 -w];
        }
    }
    //copying from the reflected to the image
    for (int h = 0 ; h < height ; h++)
    {
        for (int w = 0 ; w < width ; w++)
        {
           image[h][w] = reflected[h][w];
        }
    }
    return;
}

void print_image(int height, int width, int image[height][width])
{
    for (int j = 0; j < height; j++)
    {
        printf ("\t");
        for (int i = 0; i < width; i++)
            printf ("%d ", image[j][i]);

        printf ("\n");
    }
    printf ("\n");
}

int main ()
{
    int image[9][3] =
    {{255, 0, 0,},
     {255, 0, 0,},
     {255, 0, 0,},
     {0, 255, 0,},
     {0, 255, 0,},
     {0, 255, 0,},
     {0, 0, 255,},
     {0, 0, 255,},
     {0, 0, 255,}};

    printf ("image = \n");
    print_image (9, 3, image);

    reflect(9, 3, image);

    printf ("reflected = \n");
    print_image (9, 3, image);
}

这是预期的输出吗?

$ gcc main.c && ./a.out
image = 
    255 0 0 
    255 0 0 
    255 0 0 
    0 255 0 
    0 255 0 
    0 255 0 
    0 0 255 
    0 0 255 
    0 0 255 

reflected = 
    0 0 255 
    0 0 255 
    0 0 255 
    0 255 0 
    0 255 0 
    0 255 0 
    255 0 0 
    255 0 0 
    255 0 0

相关问题