2012-06-24 125 views
0

我有一個雙重對象的NSArray ....我目前有一個for循環來通過NSArray並將其平均。我正在尋找一種方法來確定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; 

任何幫助,建議或代碼,將不勝感激。

+2

一些友善的筆記風格,提供良好的性質:1.第一行創建一個不必要的數組。您可以簡單地將Array設置爲fetchedObjects的返回值。 2.循環中的最後一行可以使用一元賦值運算符:aveRatingScore + = two; 3.檢查Objective-C「快速枚舉」。有了這一切,您的整個循環可以是一行:aveRatingScore + = [object.rating doubleValue] –

回答

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位僅用於避免涉及零的誤報。

+0

+1,因爲您使用的是快速枚舉。 – EmilioPelaez

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

您的代碼導致崩潰(valueForKey :),我已將其更新爲valueForKeyPath。 –

相關問題