我一直试图检查NSInteger是奇数还是偶数。我找到了一种使用C来实现它的方法,但它不适用于Objective-C。我该怎么做?
NSInteger
被定义为int
(或某些环境中的long
)。所以检查奇怪就像普通的int:
NSInteger num;
if (num % 2)
// odd
else
// even
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");
}
据我所知。 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
其他答案应该有效。也许这是你的makefile或其他东西的问题。在那段代码之外思考。
如果所有其他方法都失败,则将整数声明为int。您不必将其声明为NSInteger。
使用“%”运算符。从本质上讲,当你划分数字时,它会计算出余数。所以:
2号
如果数字是偶数,则= 0,因为偶数除以2没有余数。如果它不= 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]);
希望能帮助到你 !!!
您可以将模块运算符与if-else语句一起使用,例如:
if ( (number %2) == 0 ){
printf("Your number is even");
} else {
printf("Your number is odd");
}