【问题标题】:Create array of negative numbers in Objective C在Objective C中创建负数数组
【发布时间】:2019-05-22 12:24:53
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      使用enumerateObjectsUsingBlock的解决方案的另一种方法,

      __block NSInteger positiveCount = 0;
      __block NSInteger zeroCount = 0;
      __block NSInteger negativeCount = 0;
      
      NSArray *arr = [NSArray arrayWithObjects:@-4,@-3,@-9,@0,@4,@1, nil];
      
      [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
          NSInteger value = ((NSNumber *)obj).integerValue;
          if (value > 0) {
              positiveCount += 1;
          } else if (value < 0) {
              negativeCount += 1;
          } else {
              zeroCount += 1;
          }
      }];
      NSLog(@"%ld",(long)positiveCount);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-03
        • 2013-05-17
        相关资源
        最近更新 更多