美文网首页
ios如何获取数组中的最大值和最小值

ios如何获取数组中的最大值和最小值

作者: 陈大帅 | 来源:发表于2022-04-08 16:32 被阅读0次

    第一种:快速求和

        NSArray * array = @[@"20",@"80",@"99",@"86",@"68",@"39",@"69",@"23",@"79",@"97"];
        
        float sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
        
        float avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
        
        float max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
        
        float min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];   
    
    

    第二种:循环遍历 拿到自己想要的索引下标

     NSArray * array = @[@"20",@"80",@"99",@"86",@"68",@"39",@"69",@"23",@"79",@"97"];
        int max_number = 0;
        int max_index = 0;
        
        int min_number = 0;
        int min_index = 0;
        
        int all = 0;
        float mid = 0;
        
        for (int i = 0; i<array.count; i++) {
            //取最大值和最大值的对应下标
            int a = [array[i] integerValue];
            if (a > max_number) {
                max_index = i;
            }
            max_number = a>max_number?a:max_number;
            //取最小值和最小值的对应下标
    
            int b = [array[i] integerValue];
            if (b<min_number) {
                min_index = i;
            }
            min_number = b<min_number?b:min_number;
            // 取平均数和总和
            int c = [array[i] integerValue];
            all += c;
            mid = all/array.count;
            
        }
    

    查看原文

    相关文章

      网友评论

          本文标题:ios如何获取数组中的最大值和最小值

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