数组求和、最大值、最小值、平均值

作者: any_where | 来源:发表于2016-05-30 16:22 被阅读193次

    数组内容

    NSArray*value =@[

    @"35.19",@"30.97",@"33.24",@"40.41",@"48.21",

    @"55.15",@"85.81",@"93.49",@"99.75",@"91.76",

    @"147.72",@"140.19",@"169.67",@"183.78",@"192.18",

    @"183.58",@"189.89"];

    1.第一种

    NSNumber*sum = [valuevalueForKeyPath:@"@sum.floatValue"];

    NSNumber*avg = [valuevalueForKeyPath:@"@avg.floatValue"];

    NSNumber* max =[valuevalueForKeyPath:@"@max.floatValue"];

    NSNumber* min =[valuevalueForKeyPath:@"@min.floatValue"];

    NSLog(@"sum = %.2f,\navg = %.2f,\nmax = %.2f,\nmin = %.2f",[sum floatValue],[avg floatValue],[max floatValue],[min floatValue]);

    结果

    sum = 1820.99,

    avg = 107.12,

    max = 192.18,

    min = 30.97

    2.第二种

    NSArray*aa = [valuesortedArrayUsingComparator:^NSComparisonResult(id_Nonnullobj1,id_Nonnullobj2) {

    if([obj1integerValue] > [obj2integerValue]) {

    return(NSComparisonResult)NSOrderedDescending;

    }

    if([obj1integerValue] < [obj2integerValue]) {

    return(NSComparisonResult)NSOrderedAscending;

    }

    return(NSComparisonResult)NSOrderedSame;

    }];

    3.第三种

    NSArray*a = [valuesortedArrayWithOptions:NSSortStableusingComparator:^NSComparisonResult(id_Nonnullobj1,id_Nonnullobj2) {

    if([obj1integerValue] > [obj2integerValue]) {

    return(NSComparisonResult)NSOrderedDescending;

    }

    if([obj1integerValue] < [obj2integerValue]) {

    return(NSComparisonResult)NSOrderedAscending;

    }

    return(NSComparisonResult)NSOrderedSame;

    }];

    4.第四种

    NSArray*a = [valuesortedArrayWithOptions:NSSortStableusingComparator:^NSComparisonResult(id_Nonnullobj1,id_Nonnullobj2) {

    return[[NSNumbernumberWithFloat:[obj1floatValue]]compare:[NSNumbernumberWithFloat:[obj2floatValue]]];

    }];

    5.第五种

    NSArray*a = [valuesortedArrayWithOptions:NSSortStableusingComparator:^NSComparisonResult(id_Nonnullobj1,id_Nonnullobj2) {

    return[obj1compare:obj2options:NSNumericSearch];

    }];

    相关文章

      网友评论

        本文标题:数组求和、最大值、最小值、平均值

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