iOS 获取数组最大值最小值

2020-07-16  本文已影响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

上一篇下一篇

猜你喜欢

热点阅读