Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 乘积/乘法NSMutableArray值_Ios_Objective C_Cocoa Touch - Fatal编程技术网

Ios 乘积/乘法NSMutableArray值

Ios 乘积/乘法NSMutableArray值,ios,objective-c,cocoa-touch,Ios,Objective C,Cocoa Touch,我有一个NSMutableArray,我需要把里面所有的数字都积起来。 我就是不知道该怎么做。 另外,我对objective-c很陌生,所以请尽可能清楚。 谢谢,H2CO3是正确的。为了完整起见,试试看 NSNumber * sum = [numArray valueForKeyPath:@"@sum.self"]; numArray是你的阵列 您可以查看NSExpression类,它功能强大,您可以根据自己的需要对其进行自定义。它还支持许多内置功能,例如: NSArray *nums = @

我有一个NSMutableArray,我需要把里面所有的数字都积起来。 我就是不知道该怎么做。 另外,我对objective-c很陌生,所以请尽可能清楚。
谢谢,H2CO3是正确的。为了完整起见,试试看

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

numArray是你的阵列

您可以查看NSExpression类,它功能强大,您可以根据自己的需要对其进行自定义。它还支持许多内置功能,例如:

NSArray *nums = @[@1, @2, @3, @4, @5];
NSExpression *expression = [NSExpression expressionForFunction:@"sum:" arguments:@[[NSExpression expressionForConstantValue:nums]]];
id result = [expression expressionValueWithObject:nil context:nil];

是的,你也可以这样做

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);

假设我们正在处理int值

int sum = 1;
for (NSNumber *num in someArray) {
    sum *= [num intValue];
}
NSLog(@"%d", sum);
int和intValue可以很容易地替换为double和doubleValue或任何适合您需要的东西。someArray是值数组的名称

然而,如果。。。这个问题措词不当,我们都误解了,您需要一个新数组,其索引包含其他两个数组中相同索引处的对象的值的乘积,然后您需要类似以下内容:

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

这与Xcode无关。除此之外,这也不是非常客观的。将结果初始化为1,然后循环数组并将结果乘以数组中的下一个元素。需要注意的是,在不知道如何先用C或Java编程的情况下用Objective-C编程是很危险的。你会发现各种各样的坏习惯和误解。应该指出的是,尽管使用NSExpression或KVC之类的东西是可以的,但上述内容对新手来说更有效,也更容易理解。其中一个技巧是,数字将存储为NSNumber或NSString值,因此需要应用integerValue以获得可以在算术表达式中操作的NSInteger。循环本身是每个程序员都应该知道的第二天性。