我创建了一个由正数、负数和零组成的数组,但它将数组中的所有元素都视为正数。在代码中,positiveCount 为 6。如何在 Objective-C 中将负数放入数组中?
NSInteger positiveCount = 0;
NSInteger zeroCount = 0;
NSInteger negativeCount = 0;
NSArray *arr = [NSArray arrayWithObjects:@-4,@-3,@-9,@0,@4,@1, nil];
for (NSInteger i = 0; i < arr.count; i++){
NSLog(@"%d",arr[i]);
if (arr[i] > 0)
{
positiveCount += 1;
} else if (arr[i] < 0){
negativeCount += 1;
} else {
zeroCount += 1;
}
}
NSLog(@"%d",positiveCount);
最佳答案
你数组中的元素不是数字,它们是NSNumber
实例,也就是指针。指针始终为正:
for (NSNumber* number in arr) {
NSInteger intValue = number.integerValue;
NSLog(@"%d", intValue);
if (intValue > 0) {
positiveCount += 1;
} else if (intValue < 0) {
negativeCount += 1;
} else {
zeroCount += 1;
}
}
关于ios - 在 Objective C 中创建负数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894801/