使用NSArray获取对象的最小值和最大值

时间:2012-06-24 01:01:05

标签: iphone ios4 nsarray ios5

我有一个双重对象的NSArray ....我目前有一个for循环来通过NSArray并对它们进行平均。我正在寻找一种方法来确定NSArray中的最小值和最大值,并且不知道从哪里开始...下面是我必须获得平均值的当前代码。

NSArray *TheArray = [[NSArray alloc] initWithArray:self.fetchedResultsController.fetchedObjects];
    int TotalVisitors = [TheArray count];
    double aveRatingSacore = 0;

for (int i = 0; i < TotalVisitors; i++)
        {
            Visitor *object = [TheArray objectAtIndex:i];
            double two = [object.rating doubleValue];
            aveRatingSacore = aveRatingSacore + two;
        }

        aveRatingSacore = aveRatingSacore/TotalVisitors;

非常感谢任何帮助,建议或代码。

3 个答案:

答案 0 :(得分:12)

这个怎么样?

NSArray *fetchedObjects = self.fetchedResultsController.fetchedObjects;
double avg = [[fetchedObjects valueForKeyPath: @"@avg.price"] doubleValue];
double min = [[fetchedObjects valueForKeyPath: @"@min.price"] doubleValue];
double max = [[fetchedObjects valueForKeyPath: @"@max.price"] doubleValue];

答案 1 :(得分:3)

NSArray *TheArray = [[NSArray alloc] initWithArray:self.fetchedResultsController.fetchedObjects];
int TotalVisitors = [TheArray count];
double aveRatingSacore = 0;
double minScore = 0;
double maxScore = 0;

for (int i = 0; i < TotalVisitors; i++)
        { 
            Visitor *object = [TheArray objectAtIndex:i];
            double two = [object.rating doubleValue];
            aveRatingSacore = aveRatingSacore + two;
            if (i == 0) {
                minScore = two;
                maxScore = two;
                continue;
            }
            if (two < minScore) {
                 minScore = two;
            }
            if (two > maxScore) {
                 maxScore = two;
            }
        }

aveRatingSacore = aveRatingSacore/TotalVisitors;

答案 2 :(得分:3)

设置两个双打,一个用于分钟,一个用于最大值。然后在每次迭代中,将每个设置为现有最小值/最大值的最小值/最大值以及迭代中的当前对象。

double theMin;
double theMax;
BOOL firstTime = YES;
for(Visitor *object in TheArray) {
  if(firstTime) {
    theMin = theMax = [object.rating doubleValue];
    firstTime = NO;
    coninue;
  }
  theMin = fmin(theMin, [object.rating doubleValue]);
  theMax = fmax(theMax, [object.rating doubleValue]);
}

firstTime位仅用于避免涉及零的误报。