在编码过程中,我们通常碰到一组数据,需要自己简单的处理下,拿到数组中的总和,大小和平均值数据。
1.简单粗暴的方法,快速求和。
NSArray * array = @[@"35",@"786",@"111",@"73",@"80",@"58",@"34",@"3"]; 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]; NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
2.通过算法,for循环的方式获取,并且拿到自己想要的索引下标。
NSArray * array = @[@"35",@"786",@"111",@"73",@"80",@"58",@"34",@"3"]; 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; }
简单介绍了两种获取数组最大最小值,平均值和总和的方法。