对数组求和 - Objective-C [英] Sum an Array - Objective-C
问题描述
我刚刚开始,我正在寻找一种简单的方法来总结一个简单的数组.我已经阅读了关于键值编码的苹果开发者网站,但我不明白如何将它应用到我的数组中,或者这是否是求和的合适方法.
I'm just starting out and I'm looking for an easy way to sum a simple array. I've read into apple developer site on key value coding and I don't understand how to apply that to my array or if that's the appropriate way to sum this.
我使用键值编码的绊脚石是 .keypathToProperty - 我可以理解您需要在二维数组中进一步引用,但它们不显示数组代码,只显示行标题的键路径所以我还想不通.
My stumbling block with the key value coding is the .keypathToProperty - I can sort of understand that you need a further reference in a 2D array but they don't show the array code, only the keypath to the title of the row so I can't figure it out yet.
NSMutableArray *numArray = [NSMutableArray arrayWithCapacity:4];
[numArray addObject:num1];
[numArray addObject:num2];
[numArray addObject:num3];
[numArray addObject:num4];
感谢您的回复!
谢谢
格雷厄姆
推荐答案
自动执行的方法是:
NSNumber * sum = [numArray valueForKeyPath:@"@sum.self"];
但如果您刚刚开始,我建议您避免使用集合键路径运算符并采用更简单的方法:
But if you're just starting out, I would recommend avoiding the collection key-path operators and go for the more simple way:
double sum = 0;
for (NSNumber * n in numArray) {
sum += [n doubleValue];
}
这篇关于对数组求和 - Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!