-1

I want to create an integer whose total value cannot go beyond a range of numbers when added to and subtracted from. For example, if the "total_value" started at 0 (of a total possible range between -5 and 5), and then, using a button that added 1 to the total value, I got to 5, if I was to press it again it would not go to six but either reset to 5 or block another input of +1.

How would I go about achieving something to this effect?

Liam

Liam
  • 167
  • 1
  • 2
  • 9

3 Answers3

2

You are probably looking for the constrain() macro (an existing implantation of clamp logic, credit goes to @Edgar Bonet)

value = constrain(value + input, -5, 5);

If you get tired of writing constrain() you can even wrap it in a new type (which might be over-engeneering), producing something like following(code not tested)

template<typename T>
struct BoundValue {
    T value;
    const T vmin, vmax;
    //similar for other operators +,/,-=,...
    decltype(*this)& operator+=(T operand) { value = constrain(value + operand, vmin, vmax); return *this; }
    operator T() const { return value; }
    BoundValue(const T& vmin, const T& vmax) : vmin(vmin), vmax(vmax) {}
    BoundValue& operator=(const T& other) { value = constrain(other, vmin, vmax); return *this; }
};

and use like variable of its argument type

BoundValue<int> val(-5, 5);
val += 6;//val = 5
wondra
  • 158
  • 5
1

For adding:

total_value = total_value + 1;
if (total_value > 5)
  total_value = 5;

And for subtracting:

total_value = total_value - 1;
if (total_value < -5)
  total_value = -5;

You may find a C or C++ tutorial very helpful.


Another method for adding:

if (total_value < 5)
  total_value++;

And for subtracting:

if (total_value > -5)
  total_value--;
Nick Gammon
  • 38,901
  • 13
  • 69
  • 125
0

You can not create a number with arbitrary upper and lower limits. It is common in the C language to create an integer comprised of 16 bits. Such an integer has a minimum of:

-(2^15) = -32768

...and maximum of:

(2^15) - 1 = +32767 

Instead, after pressing the positive button, consider testing if "total_value" is 5 and skipping adding 1 to "total_value" if TRUE. Conversely, after pressing the negative button, consider testing if "total_value" is -5 and skipping subtracting 1 from "total_value" if TRUE.

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81
st2000
  • 7,513
  • 2
  • 13
  • 19