hanimal_p
hanimal_p

Reputation: 303

If Statement conditioning

ok, this is a bit of a crazy ask, but I have been banging my head all day and there must be an easier way of doing this!

I have 2 values and I want to test these values against each other but there could be a + or - 10 difference between them that is acceptable.

All I keep thinking is that I will have to write a huge statement with lots of OR's in there i.e

if (red = red1) || (red == red1 + 1) || (red == red1 + 2) etc.....

Please someone put me out of my misery and tell me there is an easier way!!!

Upvotes: 0

Views: 2188

Answers (2)

Tim Dean
Tim Dean

Reputation: 8292

Simple: Assuming these are integer values:

if (abs(red - red1) <= 10) {
}

If instead you have float values:

if (fabs(red - red1) <= 10.0) {
}

There are several other absolute value functions available depending on the type of values. See this SO answer for more info

Upvotes: 0

aioobe
aioobe

Reputation: 421220

Check if the absolute value of the difference between the two numbers is less than 10.

if (abs(red - red1) <= 10)
    ...

Upvotes: 3

Related Questions