I am having trouble thinking through this simple problem, I am subtracting 2 variables, both have a range of 0 to 15 and I was using the constrain function to keep the result of the calculation between 0 and 15 (intending to code - if the subtraction results in a negative value then return 0) ie:
byte result = x - y;
result = constrain(result, 0, 15);
But in this code, if the result of the subtraction is a negative value I get the upper end of the constrain function (15) as the output where I thought I would get 0.
How would I code this argument correctly?
Thanks in advance!
problem with byte is that if you subtract 10 from 5, you don't get -5, because bytes can't represent -5, they can only do 0 - 255, and if you go over the limit, it wraps around, so 5 - 10 = 250 (give or take one)
I would suggest the following code:
if (y > x) {
result = 0;
} else {
result = x -y;
}
or, if you want to simplify it, you could use the ? : expression:
Thanks to everyone for the replies, all nice tips.
TRex:
problem with byte is that if you subtract 10 from 5, you don't get -5, because bytes can't represent -5, they can only do 0 - 255, and if you go over the limit, it wraps around, so 5 - 10 = 250 (give or take one)
I would suggest the following code:
if (y > x) {
result = 0;
} else {
result = x -y;
}
or, if you want to simplify it, you could use the ? : expression:
result = (y > x) ? 0 : x-y;
[code]
[/code]
Thank you very much T-Rex, this is the perfect solution for this application. I didn't realise that byte loops back around to 255 when you pass 0 and that was causing the confusion so this ensures that I get 0 if the result is negative.