【问题标题】:use NSArray to get minimum and maximum values of objects使用 NSArray 获取对象的最小值和最大值
【发布时间】:2012-06-24 01:01:04
【问题描述】:

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

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

【问题讨论】:

  • 一些关于风格的友好注释,以良好的性质提供: 1. 第一行创建了一个不必要的数组。您可以简单地将 theArray 设置为 fetchedObjects 的返回值。 2. 循环中的最后一行可以使用一元赋值运算符: aveRatingScore += two; 3.查看Objective-C“快速枚举”。有了这一切,你的整个循环可能只有一行: aveRatingScore += [object.rating doubleValue]

标签: iphone ios4 nsarray ios5


【解决方案1】:

这个怎么样?

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];

【讨论】:

  • 您的代码导致崩溃 (valueForKey:),我已将其更新为 valueForKeyPath。
【解决方案2】:

设置两个双打,一个用于最小,一个用于最大。然后在每次迭代中,将 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 位只是为了避免涉及零的误报。

【讨论】:

    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多