문제

I have an NSMutableArray of NSNumbers that I have created using this code.

if (countMArray == nil) {
        countMArray = [[NSMutableArray alloc] init];
    }
    if ([countMArray count] == 10) {
        [countMArray removeObjectAtIndex:0];
    }
    NSNumber *currentX = [NSNumber numberWithDouble:x];
    [countMArray addObject:currentX];

    NSLog(@"%@", countMArray);

this is how my array looks.

2014-05-02 20:34:35.065 MotionGraphs[3721:60b] (
    "0.0292816162109375",
    "0.0315704345703125",
    "0.03271484375",
    "0.030517578125",
    "0.03094482421875",
    "0.0302886962890625",
    "0.03192138671875",
    "0.0306396484375",
    "0.03094482421875",
    "0.02874755859375"
)

I would like to find the average of the 10 numbers, I understand the mathematics behind it are simple: add all the values then divide by 10. However, I would like to know the best way to attempt this.

도움이 되었습니까?

해결책

If you simply wanted to average all the countMArray in the numbers array, you could use KVC collection operator:

NSNumber *average = [countMArray valueForKeyPath:@"@avg.self"];

다른 팁

You should use if array contains NSNumber

NSNumber *average = [countMArray valueForKeyPath:@"@avg.doubleValue"];

But you are having NSStrings, so use this below method

-(double)avgOfArray:(NSArray*)array{

    double total=0.0;

    for (NSString *aString in array) {

        total+=[aString doubleValue];

    }

    return ([array count]>0)?(total/[array count]):total;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top