Product/Multiplication NSMutableArray Values [clos

2019-09-20 14:02发布

I have an NSMutableArray and I need to make the product of all the numbers inside it. I just can't understand how to do. PS. I'm quite new with objective-c so be as clear as possible. Thank's

4条回答
Summer. ? 凉城
2楼-- · 2019-09-20 14:07

H2CO3 is right. For the sake of completeness try

NSNumber * sum = [numArray valueForKeyPath:@"@sum.self"];

where numArray is your array.

查看更多
太酷不给撩
3楼-- · 2019-09-20 14:16

You can have a look on NSExpression class it's very powerfull and you can customize it to your requirements. It's also support many build in functions, for example:

NSArray *nums = @[@1, @2, @3, @4, @5];
NSExpression *expression = [NSExpression expressionForFunction:@"sum:" arguments:@[[NSExpression expressionForConstantValue:nums]]];
id result = [expression expressionValueWithObject:nil context:nil];
查看更多
够拽才男人
4楼-- · 2019-09-20 14:23

yes you can also do like this..

int result=1;
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil];
for (int i=0; i<[array count]; i++) {
result*=[[array objectAtIndex:i] integerValue];
}
NSLog(@"%d     ",result);
查看更多
做个烂人
5楼-- · 2019-09-20 14:23

Assuming we're working with int values...

int sum = 1;
for (NSNumber *num in someArray) {
    sum *= [num intValue];
}
NSLog(@"%d", sum);

int and intValue can easily be replaced with double and doubleValue or whatever is appropriate for what you need. someArray is the name of the array of values.


If, however... the question is poorly worded and we've all misunderstood, and you need a new array whose indices contain the product of the values of the objects at the same indices in two other arrays, then you're looking for something more like this:

NSMutableArray *productArray = [NSMutableArray array];
for(int i=0; i<[arr1 count]; ++i) {
    int product = [[arr1 objectAtIndex:i] intValue] * [[arr2 objectAtIndex:i]
        intValue];
    [productArray addObject: [NSNumber numberWithInt: product]];
}
查看更多
登录 后发表回答