我正在努力在Objective-C中平均任意多个数字,到目前为止这是我的方法:
-(double)average:(double)num, ...
{
va_list args;
va_start(args, num);
double currentAverage = num;
long long timesAveraged = 1;
for(double d in args)
currentAverage = ((currentAverage * timesAveraged) + d) / ++timesAveraged;//Error occurs on this line
return currentAverage;
}
但是,当我编译它时,我收到一条错误,指出“Selector element does not have a valid object type
”,所以我的第一个解决方案是将方法更改为以下内容:
-(double)average:(double)num, ...
{
va_list args;
va_start(args, num);
double currentAverage = num;
long long timesAveraged = 1;
for(NSNumber *d in args)
currentAverage = ((currentAverage * timesAveraged) + [d doubleValue]) / ++timesAveraged;//Error occurs on this line
return currentAverage;
}
然而,现在它给了我一个令人不安的类似错误“Expression does not have a valid object type
”。
我显然做错了。有关如何做到这一点的任何建议吗?
我已经能够通过编写这样的方法来编译文件:
-(double)average:(double)num, ...
{
va_list args;
va_start(args, num);
double currentAverage = num;
long long timesAveraged = 1;
for (NSNumber *arg = [NSNumber numberWithDouble:num]; arg != nil; arg = va_arg(args, NSNumber*))
{
currentAverage = ((currentAverage * timesAveraged) + [arg doubleValue]) / ++timesAveraged;
}
va_end(args);
return currentAverage;
}
答案 0 :(得分:0)
由于trudyscousin提到快速枚举在这里不起作用。您还应该使用va_arg
从参数列表中提取数据。在此处阅读更多相关信息:http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html