Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top