2010-06-17 111 views
8

如何在objective-c编码中告诉整数是正数还是负数。我这样做,以便我可以写一个“if”声明,说明如果这个整数是正数,那么做这个,如果它的负数做到这一点。检查整数是正数还是负数 - Objective C

感谢,

凯文

+9

你忘了零,这既不是积极的也不是消极的? – JWWalker 2010-06-17 21:22:54

回答

33
if (x >= 0) 
{ 
    // do positive stuff 
} 
else 
{ 
    // do negative stuff 
} 

如果要单独处理x == 0情况下(因为0既不是正面也不是负面的),那么你可以做这样的:

if (x > 0) 
{ 
    // do positive stuff 
} 
else if (x == 0) 
{ 
    // do zero stuff 
} 
else 
{ 
    // do negative stuff 
} 
+1

0现在是正面的吗? :) – 2010-06-17 21:21:30

+7

大多数数学家接受0作为正值 – 2010-06-17 21:23:19

+5

直到他们发现像log(x)这样的函数。 – Eiko 2010-06-17 21:31:01

2

也许我错过了一些东西,我不明白这个问题,但不是这只是

if(value >= 0) 
{ 
} 
else 
{ 
} 
2
-(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"); 
} 

;-)

虽然严重,只是用

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

不要过分方法ANS属性和辅助功能为琐碎的事情。