我有一个大NSArray
含有NSNumbers
像3, 4, 20, 10, 1, 100,
等...
我如何获得这些NSNumbers的总和(3 + 4 + 20 + 10 + 1 + 100 + etc...)
作为一个总NSInteger
?
谢谢!
我有一个大NSArray
含有NSNumbers
像3, 4, 20, 10, 1, 100,
等...
我如何获得这些NSNumbers的总和(3 + 4 + 20 + 10 + 1 + 100 + etc...)
作为一个总NSInteger
?
谢谢!
NSInteger sum = 0;
for (NSNumber *num in myArray) {
sum += [num intValue];
}
您可以使用此:
NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;
通过阵列迭代
int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
sum += [[array objectAtIndex:i] integerValue];
}
[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]
int total = 0;
for (NSNumber *number in array)
{
total += [number intValue];
}
可能这将帮助你