Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C: why my output isn't rounding up using the round() function in math.h?

I’m writing a grayscale function and I’m using round() to round the average of RGB colours but when testing it the round function doesn’t round up answers > x.5 instead it rounds everything down.

I have tried changing my int avg to float avg and using the round(), didn’t work. I tried using roundf(), didn’t work. when values of red, green and blue are 27, 28, 28 for example I get avg 27 instead of the correct 28.

My code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    int avg = 0;
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            avg = round((image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtBlue) / 3);
            image[i][j].rgbtRed = avg;
            image[i][j].rgbtGreen = avg;
            image[i][j].rgbtBlue = avg;
        }
    }
    return;
}

>Solution :

round((image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtBlue) / 3)

The values you’re adding together are all integers. You’re then dividing by an integer. The result is an integer before round is ever called. When round is called, 27 becomes 27.0, but that just rounds back to 27.

In your example, 27 + 28 + 28 = 83. 83 / 3 is 27.666…7. But integer math doesn’t consider the fractional part so you get 27.

Simple solution: divide by a floating point number.

round((image[i][j].rgbtRed + image[i][j].rgbtGreen + image[i][j].rgbtBlue) / 3.0)

You will now get a floating point number back from the division which can be rounded.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading