So I am a little stuck on the Greyscale protion of the Pset4. I have the code in place as follows...

void grayscale(int height, int width, RGBTRIPLE image[height][width])
    for (int i = 0; i < height; i++)
        for (int j = 0; j < width; j++ )
            int red = image[i][j].rgbtRed;
            int green = image[i][j].rgbtGreen;
            int blue = image[i][j].rgbtBlue;

            int total = red + green + blue;
            float average = total / 3;
            image[i][j].rgbtRed = average;
            image[i][j].rgbtGreen = average;
            image[i][j].rgbtBlue = average;

So when I run Check 50 on the problem, this happens...

:( grayscale correctly filters single pixel without whole number average

expected "28 28 28\n", not "27 27 27\n" 

What part of my code is not causing the average to be produced correctly?

NB:/ I have tried using the round function but that does the same thing.

Thanks in advance



Did you happen to notice that the incorrect results all happen to be 1 less than the correct answers? That's a big clue.

The problem lies here.

float average = total / 3;

Since total is an int and "3" is an int, this is integer division. Rounding won't change it, since the result of the division is an integer that will always be the result of truncating the decimal portion of the float to produce the next lower int.

Now, if it was "3.0" instead of "3", or total were cast as a float, it would cause regular division to be used instead of integer division. The rounding function could then be applied, or even incorporated into the same calculation.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Thank you good Sir. I cast the total as a float and rounded the average function. That solved my issue. Now... Onto Blur sigh
    – EdCase
    Aug 27 '20 at 8:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .