views:

189

answers:

3

Hello,

How can I tell in objective-c coding if an integer is positive or negative. I'm doing this so that I can write an "if" statement stating that if this integer is positive then do this, and if its negative do this.

Thanks,

Kevin

+5  A: 
if (x >= 0)
{
    // do positive stuff
}
else
{
    // do negative stuff
}

If you want to treat the x == 0 case separately (since 0 is neither positive nor negative), then you can do it like this:

if (x > 0)
{
    // do positive stuff
}
else if (x == 0)
{
    // do zero stuff
}
else
{
    // do negative stuff
}
Paul R
0 is positive now? :)
BlueRaja - Danny Pflughoeft
most mathematicians accept 0 as a positive value
Deniz Acay
Until they discover functions like log(x).
Eiko
@BlueRaja - Danny Pflughoeft: well it doesn't have a `-` in front of if, so that's good enough for me. ;-)
Paul R
@Deniz: Mathematicians say 0 is a *non-negative* value; but it's not *positive*.
BlueRaja - Danny Pflughoeft
@BlueRaja - Danny Pflughoeft: if...else statemens evaluate logical expressions as true/false, so for computer "if it is not negative, it is positive".
Deniz Acay
@Deniz Acay: Then please do a if(-1) printf("Wow I'm positive"); and fasten your seatbelts.... C takes everything != 0 as true.
Eiko
That's why i hate C :)
Deniz Acay
@Deniz Acay: I've never heard of mathematicians accepting 0 as positive (and I used to be a math professor). Mathematicians use the word "nonnegative" all the time. They wouldn't need the word if it meant the same thing as "negative".
JWWalker
Looks like i understood this "non-negative" word as "positive", so thanks for correction :)
Deniz Acay
+1  A: 

Maybe I am missing something and I don't understand the quesiton but isn't this just

if(value >= 0)
{
}
else
{
}
Steve Sheldon
+1  A: 
-(void) tellTheSign:(int)aNumber
{
   printf("The number is zero!\n");
   int test = 1/aNumber;
   printf("No wait... it is positive!\n");
   int test2 = 1/(aNumber - abs(aNumber));
   printf("Sorry again, it is negative!\n");
}

;-)

Seriously though, just use

if (x < 0) {
// ...
} else if (x == 0) {
// ...
} else {
// ...
}

Don't overdo methods ans properties and helper functions for trivial things.

Eiko