views:

42

answers:

2

Hello!

I have a set of checks to perform certain tasks.

// tempDouble is a (double), hour is an int

if (tempDouble > 60.0 && (hour >= 6 || hour <= 17)) { //CLEAR
    NSLog(@"CLEAR");
} 

else if (tempDouble > 60.0 && (hour < 6 || hour > 17)) { //NIGHT_CLEAR
    NSLog(@"NIGHT_CLEAR");
}

else if (tempDouble <= 60.0 && (hour >= 6 || hour <= 17)) { //CLOUDY
    NSLog(@"CLOUDY");
}

else if (tempDouble > 60.0 && (hour < 6 || hour > 17)) { //NIGHT_CLOUDY
    NSLog(@"NIGHT_CLOUDY"); 
}

When I have a temp of 76.3 and an hour of 2, for example, I'd expect it to jump to NIGHT_CLEAR, but it actually goes to CLEAR. Did I set up my comparisons wrongly?

Thanks in advance for this simple question!

+6  A: 
(hour >= 6 || hour <= 17)

is always true. All real numbers are either greater than or equal to 6 or less than or equal to 17 (some are both). I think you want:

(hour >= 6 && hour <= 17)

The same also applies to CLOUDY.

Matthew Flaschen
Exactly, can't believe I didn't see that before!
willingfamily
Thank you very much!
willingfamily
+2  A: 

Some of your ||'s might be better off being &&'s.

Perhaps what you want is...

if (tempDouble > 60.0 && (hour >= 6 && hour <= 17)) { //CLEAR
    NSLog(@"CLEAR");
} 

else if (tempDouble > 60.0 && (hour < 6 && hour > 17)) { //NIGHT_CLEAR
    NSLog(@"NIGHT_CLEAR");
}

else if (tempDouble <= 60.0 && (hour >= 6 || hour <= 17)) { //CLOUDY
    NSLog(@"CLOUDY");
}

else if (tempDouble > 60.0 && (hour < 6 || hour > 17)) { //NIGHT_CLOUDY
    NSLog(@"NIGHT_CLOUDY"); 
}
jojaba
eldarerathis
willingfamily