Andrew
Andrew

Reputation: 552

How to compare int values?

I would like to know how to compare int values.

I would like to know that once I compare both 2 int values, I would like to know how far apart these 2 values are and if it is possible to put this in a 'if' statement.

The only problem I have is that (lets say int HELLO), HELLO's value always changes at random, so I would like to know how do I always compare HELLO's value and a different int's value on the go, so that at any moment if the result of both values are only 50 numbers off (negative or positive), it would trigger let's say timer2->Stop();.

Thank you.

Upvotes: 0

Views: 157

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

The distance between two int numbers is calculated as an absolute value of their difference:

int dist = abs(value1 - value2);

You can put it in an if statement or do anything you wish with the result:

if (abs(value1 - value2) > 50) ...

Upvotes: 1

Deco
Deco

Reputation: 3321

If you have two int values, then you can subtract them to find out the difference between the two. Then in your if-test you just check if they are within 50 of each other and then execute the code...

Here's some pseudocode for you to work off of:

int valueOne = 100;
int valueTwo = 50;

int differenceBetweenValues = valueOne - valueTwo;

if ( (differenceBetweenValues >= 50) || (differenceBetweenValues >= -50) ) {
   timer2->Stop();
}

You could then make that as a function and pass your values in (as you've stated they're different each time).

Upvotes: 1

Related Questions