检查NSInteger是奇数还是偶数

时间:2010-04-23 06:15:36

标签: objective-c cocoa-touch

我一直在尝试检查NSInteger是奇数还是偶数。我找到了一种使用C来实现它的方法,但它不适用于Objective-C。我该怎么做?

7 个答案:

答案 0 :(得分:118)

NSInteger在某些环境中定义为int(或long)。所以检查奇怪就像普通的int:

NSInteger num;
if (num % 2)
  // odd
else
  // even

答案 1 :(得分:18)

NSInteger n = 5;

NSLog(@"%s", n & 1 ? "odd" : "even");

或使用if

if (n & 1) {
  ; // odd
} else {
  ; // even
}

有一些输出:

if (n & 1) {
  NSLog(@"odd");
} else {
  NSLog(@"even");
}

指针示例:

NSInteger x = 7;
NSInteger *y = &x;

if (*y & 1) {
    NSLog(@"odd");
} else {
    NSLog(@"even");
}

答案 2 :(得分:9)

据我所知。与NSInteger不同,NSNumber只是一个实数整数类型的打字机:

typedef long NSInteger;

所以你应该能够做到:

NSInteger nsintvar = 77;
if ((nsintvar % 2) == 0) {
    // number is even
} else {
    // number is odd
}

这是一个完整的程序,在Cygwin下使用GNUstep编译,它说明了它:

#import <stdio.h>
#import <Foundation/NSObject.h>

int main( int argc, const char *argv[] ) {
    NSInteger num;
    for (num = 0; num < 20; num++) {
        if ((num % 2) == 0) {
            printf ("%d is even\n", num);
        } else {
            printf ("%d is odd\n", num);
        }
    }
    return 0;
}

输出:

0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
16 is even
17 is odd
18 is even
19 is odd

答案 3 :(得分:3)

那些其他答案应该有效。也许这是你的makefile或其他东西的问题。在那段代码之外思考。

如果所有其他方法都失败,则将整数声明为int。您不必将其声明为NSInteger。

答案 4 :(得分:2)

使用&#34;%&#34;运营商。从本质上讲,当你划分数字时,它会计算出余数。所以:

号码%2

如果数字是偶数,则= 0,因为偶数除以2没有余数。如果它不= 0,则必须是奇数。

答案 5 :(得分:0)

NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", nil];
// NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", nil];
// NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
// NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", nil];
// NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", nil];

NSArray *arrLeft;
NSArray *arrRight;

NSRange range;
range.location = 0;
range.length = ([arrayTotal count] % 2) ? ([arrayTotal count] / 2) + 1 : ([arrayTotal count] / 2);

arrLeft = [arrayTotal subarrayWithRange:range];

range.location = range.length;
range.length = [arrayTotal count] - range.length;

arrRight = [arrayTotal subarrayWithRange:range];

NSLog(@"Objects: %lu", (unsigned long)[arrLeft count]);
NSLog(@"%@", [arrLeft description]);

NSLog(@"Objects: %lu", (unsigned long)[arrRight count]);
NSLog(@"%@", [arrRight description]);

希望它有所帮助!!!

答案 6 :(得分:-1)

您可以将模块运算符与if-else语句一起使用,例如:

if ( (number %2) == 0 ){

printf("Your number is even");

} else {

printf("Your number is odd");

}