Make sure the value is between 0-255

This is probably very simple, but I am at a loss on how to "make sure" in this range.

So basically we have class Color

many functions to implement it.

I need this function:

Effects: Adjusts the color value between 0-255, inclusive. If the value is outside this range, you can adjust either 0 or 255, whichever is closer.

This is what I have so far:

static int correctValue(int value)
{
    if(value<0)
        value=0;
    if(value>255)
        value=255;
}

      

Sorry for such a simple question; /

+2


a source to share


8 answers


I agree with other answers with one modification; it should be an else-if statement. There is no need to check if the value is greater than 255 if you already know that it is less than 0



static unsigned char correctValue(int value)
{
    if(value<0) value=0;
    else if(value>255) value=255;
    return value;
}

      

+1


a source


It's good. I would recommend making the function clamp

reusable:

template <typename T>
void clamp(T& pValue, const T& pMin, const T& pMax)
{
    pValue = std::min(std::max(pValue, pMin), pMax);
}

template <typename T>
T clamp_copy(T pValue, const T& pMin, const T& pMax)
{
    clamp(pValue, pMin, pMax);
    return pValue;
}

      



This gives you space and copy clamp

:

int i = 50;

j = clamp_copy(i, 0, 10);
k = clamp_copy(i, 100, 1000);
clamp(i, 0, 100);

// i = 50
// j = 10
// k = 100

      

+13


a source


fair. but you missed the final return statement

static int correctValue(int value)
{
    if(value<0) return 0;
    if(value>255) return 255;
    return value;
}

      

+8


a source


committing is pretty simple using max and min:

value = std::min(255,std::max(0,value))

      

but your method must be correct as well.

+4


a source


It will work well for you. You just need to return value

at the end of your function. If you want to make it more concise, you can use a ternary expression for a little readability:

value = (value < MIN) ?
            MIN : (value > MAX) ?
                    MAX : value;

      

Where MIN

is 0, and MAX

- 255.

+2


a source


Just return the value at the bottom of your function after your ifs and you're good to go.

+1


a source


static int correctValue(int value) {
 int correctedValue;
 if (value < 0) {
        correctedValue = 0;
 } else if (value > 255) {
        correctedValue = 255;
 } else {
        correctedValue = value;
 }

 return correctedValue;

      

}

+1


a source


Instead of using int

use unsigned char

, then the value can not go below 0 or above 255.

0


a source







All Articles