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
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);
回答2:
H2CO3 is right. For the sake of completeness try
NSNumber * sum = [numArray valueForKeyPath:@"@sum.self"];
where numArray is your array.
回答3:
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:
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]];
}