tags:

views:

84

answers:

7

This works fine

if ((a >= 40 && a <= 50) || (a >= 60 && a <= 80))
// do something

How do I do the reverse of it?

if ((a < 40 && a > 50) || (a < 60 && a > 80))
// do something

The code does not work as expected. I want something like if not (condition)

+1  A: 

While I would recommend figuring out how to make it work properly (by rewriting it)

if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))

should work I believe.

SeanJA
+4  A: 
if ((a < 40 || a > 50) && (a < 60 || a > 80))
// do something
alex
aha, what is that dudes name who has the law that you used named after him. i have been trying to remember
mkoryak
@mkoryak see my answer ;)
Zed
This is one of De Morgan's laws: http://en.wikipedia.org/wiki/De_Morgan%27s_laws
0xA3
This is an accurate application of De Morgan, but the resulting expression is a bit obfuscated IMO.
system PAUSE
+11  A: 

You might want to look at De Morgan's laws.

1. !((a >= 40 && a <= 50) || (a >= 60 && a <= 80))

2. (!(a >= 40 && a <= 50) && !(a >= 60 && a <= 80))

3. ((!(a >= 40) || !(a <= 50)) && (!(a >= 60) || !(a <= 80))

4. ((a < 40 || a > 50) && (a < 60 || a > 80))


or in other words: (a < 40 || (50 < a && a < 60) || 80 < a)
Zed
+1. Several examples that all demonstrate a possible solution complete with a reference on where to get more information.
Grant Wagner
Logically correct, but the result is hard to read and it inhibits short-circuit evaluation.
system PAUSE
also I managed to combine two steps into one. now that's fixed
Zed
Much better than my quick fix
SeanJA
+1 for mentioning De Morgan's Law
Babak Naffas
A: 

You need a "OR"

if ((a < 40 || a > 50) && (a < 60 || a > 80))

Or, a NOT

if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
Dennis Cheung
A: 

You second example

if ((a < 40 && a > 50) || (a < 60 && a > 80))

doesn't make sense as a cannot be both less than 40 and greater than 50 (or less than 60 and greater than 80) at the same time.

Something like

if (!((a < 40 && a > 50) || (a < 60 && a > 80)))

or

if ((a < 40 || a > 50) && (a < 60 || a > 80))
Russ Cam
A: 

Assuming that you want the equivalent of

if ( not ((a >= 40 && a <= 50) || (a >= 60 && a <= 80)) )

then, if you think about the original expression, it should be

if (a < 40 || (a > 50 && a < 60) || a > 80)

The first expression is allowing a to be a number from 40 to 50 or from 60 to 80. Negate that in English and you want a number less than 40 or between 50 and 60 or greater than 80.

De Morgan's Laws can get you an accurate answer, but I prefer code that you can read aloud and make sense of.

system PAUSE
A: 
if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
Tobias Baaz