如何将 NSArray 的各个对象相乘并求和?

How to multiply respective objects of NSArray and get the sum?

我有一个包含数据 A=[a,b,c] 的数组和另一个包含数据 B=[d,e,f] 的数组。我需要执行这种类型的操作 a.d+ b.e+c.f (注意=这里(.)表示乘法)并得到结果。我怎样才能使用 Objective-C 做到这一点? 提前致谢。

    NSNumber *myNum1 = [NSNumber numberWithInt:1];
    NSNumber *myNum2 = [NSNumber numberWithInt:2];
    NSNumber *myNum3 = [NSNumber numberWithInt:3];

    NSArray *a = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
    NSArray *b = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
    int sum=0;
    for (int i=0; i<[a count]; i++) {
        NSLog(@"%@", (NSNumber*)[a objectAtIndex:i]);
        sum =sum +[(NSNumber*)[a objectAtIndex:i] intValue]*[(NSNumber*)[b objectAtIndex:i] intValue];
    }
    NSLog(@"Sum is %d", sum);

希望对您有所帮助

像这样定义执行乘法和加法的函数:

- (double)multiply:(NSArray <NSNumber *> *)vector1 withVector:(NSArray <NSNumber *> *)vector2 {
    NSAssert(vector1.count == vector2.count, @"Both arrays should contain the same number of elements");

    __block double result = 0;
    [vector1 enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        double first = obj.doubleValue;
        double second = vector2[idx].doubleValue;
        result += first * second;
    }];

    return result;
}

这在 NSArray 上使用了一个块枚举方法,它为我提供了索引和一个值,我可以使用它来获取第二个数组中相同索引处的值。另请注意,我使用的是类型化数组,因此在使用它们时不必将值强制转换为 NSNumbers。

现在你可以只使用函数:

NSArray *a = @[@1, @2, @3];
NSArray *b = @[@4, @5, @6];
NSArray *c = @[@1, @1, @1];

double res1 = [self multiply:a withVector:b]; // => 32.000000 
double res2 = [self multiply:b withVector:c]; // => 15.000000
double res3 = [self multiply:c withVector:a]; // => 6.000000