2012-06-24 6 views
0

이중 객체의 NSArray가 있습니다. 현재 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; 

도움, 제안 또는 코드는 크게 감사하겠습니다.

+2

친절한 스타일로 제공되는 친절한 메모 : 1. 첫 번째 줄은 불필요한 배열을 만듭니다. theArray를 fetchedObjects의 리턴으로 설정할 수 있습니다. 2. 루프의 마지막 줄은 단항 할당 연산자를 사용할 수 있습니다. aveRatingScore + = two; 3. Objective-C "빠른 열거"를 확인하십시오. 이 모든 것들을 사용하면 Fast Enumeration을 사용하기 때문에 전체 루프가 하나의 라인이 될 수 있습니다. aveRatingScore + = [object.rating doubleValue] –

답변

3

최대 2 개, 최대 1 개, 두 개를 설정하십시오. 그런 다음 각 반복에서 기존 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 비트 만 제로 관련된 가양 성을 피할 수있다.

+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로 업데이트했습니다. –

관련 문제