10

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

skaffman
  • 398,947
  • 96
  • 818
  • 769
lab12
  • 6,400
  • 21
  • 68
  • 106

4 Answers4

38
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
  • 208,748
  • 37
  • 389
  • 560
  • 5
    Until they discover functions like log(x). – Eiko Jun 17 '10 at 21:31
  • 1
    @BlueRaja - Danny Pflughoeft: well it doesn't have a `-` in front of if, so that's good enough for me. ;-) – Paul R Jun 17 '10 at 21:31
  • 8
    @Deniz: Mathematicians say 0 is a *non-negative* value; but it's not *positive*. – BlueRaja - Danny Pflughoeft Jun 17 '10 at 21:37
  • 1
    @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 Jun 17 '10 at 21:44
  • 2
    @Deniz Acay: Then please do a if(-1) printf("Wow I'm positive"); and fasten your seatbelts.... C takes everything != 0 as true. – Eiko Jun 17 '10 at 21:54
  • 3
    @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 Jun 17 '10 at 22:32
  • Looks like i understood this "non-negative" word as "positive", so thanks for correction :) – Deniz Acay Jun 18 '10 at 08:29
3

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

if(value >= 0)
{
}
else
{
}
Steve Sheldon
  • 6,421
  • 3
  • 31
  • 35
3
-(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
  • 25,601
  • 15
  • 56
  • 71
2

In Swift

var value = 5
if value.signum() == 1 {
   print("Positive value")
} else if value.signum() == -1 {
   print("Negative value")
} else if value.signum() == 0 {
   print("Zero value")
}
Sourabh Kumbhar
  • 1,034
  • 14
  • 12