P
pozz
Hi all,
I need to write a simple incrementing/decrementing function like this:
unsigned char
change( unsigned char x, unsigned char min, unsigned char max, signed char d);
x is the value to increase/decrease
min is the minimum value that x can assume
max is the maximum value that x can assume
d is positive or negative and indicates how much x must be incremented or
decremented
Of course, the return value is the new value for x.
Some examples to clarify the question:
x=10,min=0,max=20,d=5 --> 15
x=10,min=0,max=20,d=-5 --> 5
x=18,min=0,max=20,d=5 --> 2
x=18,min=5,max=20,d=5 --> 7
x= 3,min=0,max=20,d=-5 --> 19
x=10,min=8,max=20,d=-5 --> 18
I'd like a function that use only unsigned char...
Another similar question. I have a variabile x (unsigned char) and I must
increment it. The increment is stored in another variable, d (unsigned char).
x can't assume values greater than max, stored in another variable (unsigned
char).
I usually write:
if( x+d>max )
x = max;
else
x += d;
I think it's not correct because what happens when x=200, d=100 and max=220??
If I write:
if( x>max-d )
x = max;
else
x += d;
what happens when max=10 and d=20?? I need a variable greater than unsigned
char to do the temporary sum x+d? And if I use long, I need extra-long
variables?
Thank you very much for the help.
I need to write a simple incrementing/decrementing function like this:
unsigned char
change( unsigned char x, unsigned char min, unsigned char max, signed char d);
x is the value to increase/decrease
min is the minimum value that x can assume
max is the maximum value that x can assume
d is positive or negative and indicates how much x must be incremented or
decremented
Of course, the return value is the new value for x.
Some examples to clarify the question:
x=10,min=0,max=20,d=5 --> 15
x=10,min=0,max=20,d=-5 --> 5
x=18,min=0,max=20,d=5 --> 2
x=18,min=5,max=20,d=5 --> 7
x= 3,min=0,max=20,d=-5 --> 19
x=10,min=8,max=20,d=-5 --> 18
I'd like a function that use only unsigned char...
Another similar question. I have a variabile x (unsigned char) and I must
increment it. The increment is stored in another variable, d (unsigned char).
x can't assume values greater than max, stored in another variable (unsigned
char).
I usually write:
if( x+d>max )
x = max;
else
x += d;
I think it's not correct because what happens when x=200, d=100 and max=220??
If I write:
if( x>max-d )
x = max;
else
x += d;
what happens when max=10 and d=20?? I need a variable greater than unsigned
char to do the temporary sum x+d? And if I use long, I need extra-long
variables?
Thank you very much for the help.