This is probably really easy, but I'm lost on how to "make sure" it is in this range..
So basically we have class Color
and many functions to implement from it.
this function I need is:
Effects: corrects a color v开发者_StackOverflow中文版alue to be within 0-255 inclusive. If value is outside this range, adjusts to 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 ;/
It's good. I'd recommend making a clamp
function for re-usability:
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;
}
That gives you an in-place and copying 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
fair enough. but you missed the final return statement
static int correctValue(int value)
{
if(value<0) return 0;
if(value>255) return 255;
return value;
}
clamping is pretty easy using max and min:
value = std::min(255,std::max(0,value))
but your method should be correct also.
What you have will work fine. 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 at the cost of a little bit of readability:
value = (value < MIN) ?
MIN : (value > MAX) ?
MAX : value;
Where MIN
is 0 and MAX
is 255.
static int correctValue(int value) {
int correctedValue;
if (value < 0) {
correctedValue = 0;
} else if (value > 255) {
correctedValue = 255;
} else {
correctedValue = value;
}
return correctedValue;
}
I agree with the other answers, with one modification; this should be an else-if statement. There is no need to test if the value is over 255 if you already know it is less than 0
static unsigned char correctValue(int value)
{
if(value<0) value=0;
else if(value>255) value=255;
return value;
}
Just return value at the bottom of your function after your ifs and you are good.
Instead of using an int
, use an unsigned char
, the value will then be unable to go lower than 0 or higher than 255.
精彩评论