我有一个大NSArray
个NSNumbers
,如3, 4, 20, 10, 1, 100,
等...
如何将所有这些NSNumbers (3 + 4 + 20 + 10 + 1 + 100 + etc...)
的总和作为一个NSInteger
总计?
谢谢!
答案 0 :(得分:156)
您可以使用:
NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];
答案 1 :(得分:20)
NSInteger sum = 0;
for (NSNumber *num in myArray) {
sum += [num intValue];
}
答案 2 :(得分:7)
long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;
答案 3 :(得分:4)
遍历数组
int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
sum += [[array objectAtIndex:i] integerValue];
}
答案 4 :(得分:3)
[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]
答案 5 :(得分:2)
int total = 0;
for (NSNumber *number in array)
{
total += [number intValue];
}
这可能会对你有所帮助