首页 > 解决方案 > 在Objective C中创建负数数组

问题描述

我创建了一个由正数、负数和零数组成的数组,但它将数组中的所有元素都视为正数。在代码中,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);

标签: iosobjective-c

解决方案


数组中的元素不是数字,它们是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;
    }
}

推荐阅读