sudo rm -rf
sudo rm -rf

Reputation: 29524

Comparison operators not functioning as expected

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!

Upvotes: 0

Views: 122

Answers (2)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

(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.

Upvotes: 6

tidwall
tidwall

Reputation: 6949

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"); 
}

Upvotes: 1

Related Questions