NSArray 快速求和、平均值、最大值、最小值

 

在iOS开发中我们经常遇到一个需求,求一个数组的所有元素的和,最大值,最小值或者平均值,有的开发者可能第一想到的是for循环遍历求解,其实苹果提供了更简便的方式。如下:

 NSArray *arr = @[@"5",@"1",@"4",@"3",@"4",@"10",@"6",@"14",@"16",@"30",@"20",@"18"];
    int sum = [[arr valueForKeyPath:@"@sum.intValue"] intValue];//求和
    float avg = [[arr valueForKeyPath:@"@avg.floatValue"] floatValue];//求平均值
    int max = [[arr valueForKeyPath:@"@max.intValue"] intValue];//求最大值
    int min = [[arr valueForKeyPath:@"@min.intValue"] intValue];//求最小值
    NSLog(@"和:%d \n 平均值:%f \n 最大值:%d \n 最小值:%d",sum,avg,max,min);

 

posted @ 2017-04-17 13:41  iOS_Doman  阅读(1127)  评论(0编辑  收藏  举报