0

我有一个双对象的 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;

任何帮助、建议或代码将不胜感激。

4

3 回答 3

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];
于 2012-06-24T01:47:53.800 回答
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;
于 2012-06-24T01:12:34.617 回答
3

设置两个双打,一个用于最小,一个用于最大。然后在每次迭代中,将 each 设置为现有 min/max 和迭代中当前对象的 min/max。

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 位只是为了避免涉及零的误报。

于 2012-06-24T01:19:34.693 回答