美文网首页
iOS 获取数组最大值最小值

iOS 获取数组最大值最小值

作者: 清风_____ | 来源:发表于2020-07-16 17:05 被阅读0次

    1.获取数组最大值、最小值

    保证数组里存储NSNumber对象
    例如处理接口中数据:

    NSMutableArray *price = [NSMutableArray array];
        for (NSDictionary *item in arr) {
            [price addObject: [NSNumber numberWithFloat:[item[@"price"] floatValue]]];
        }
    CGFloat maxPrice = [[price valueForKeyPath:@"@max.floatValue"] floatValue];
    CGFloat minPrice = [[price valueForKeyPath:@"@min.floatValue"] floatValue];
    

    重点参数:
    @"@max.floatValue"(获取最大值),
    @"@min.floatValue"(获取最小值),
    @"@avg.floatValue" (获取平均值),
    @"@count.floatValue"(获取数组大小)

    KVC,使用"self"

    NSNumber *max=[numbers valueForKeyPath:@"@max.self"];  
    NSNumber *min=[numbers valueForKeyPath:@"@min.self"];  
    

    代码块

    __block float xmax = -MAXFLOAT;  
    __block float xmin = MAXFLOAT;  
    [numbers enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOLBOOL *stop) {  
        float x = num.floatValue;  
        if (x < xmin) xmin = x;  
        if (x > xmax) xmax = x;  
    }];  
    

    2.数组排序

    NSArray *numbers = @[@2.1, @8.1, @5.0, @0.3];  
    numbers = [numbers sortedArrayUsingSelector:@selector(compare:)];  
      
    float min = [numbers[0] floatValue];  
    float max = [[numbers lastObject] floatValue];  
    

    https://www.jianshu.com/p/38a56e08310b

    相关文章

      网友评论

          本文标题:iOS 获取数组最大值最小值

          本文链接:https://www.haomeiwen.com/subject/gqqmhktx.html