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; /
a source to share
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;
}
a source to share
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
a source to share