0

我正在研究一种在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;

}
4

1 回答 1

0

正如 trudyscousin 提到的,快速枚举在这里不起作用。您还应该使用va_arg来从参数列表中提取数据。在这里阅读更多信息:http: //cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html

于 2012-04-18T20:58:10.893 回答