带有可变参数(...)的C++方法报告错误的arg值

Qua*_*leA 1 c++ variadic-functions

我无法将变量参数正确传递给方法 - 该方法旨在选择加权分布中的随机值并返回所选结果的索引.

一个示例用法是:

int pickupType = randomManager->ByWeights( 3, 0.60f, 0.20f, 0.20f );
switch( pickupType ) {
    // ... pickupType should be 0 to 2, which we can then branch on
}
Run Code Online (Sandbox Code Playgroud)

该功能定义如下:

#include <cstdarg>

int RandomManager::ByWeights( int weightCount, ... ) {

    va_list argList;

    // Get the total of all weights
    va_start( argList, weightCount );
    float weightTotal = 0;
    for ( int i = 0; i < weightCount; i++ ) {
        weightTotal += va_arg( argList, float );
    }
    va_end( argList );

    // Roll a number in that range
    // ... (further processing - problem occurs above)
}
Run Code Online (Sandbox Code Playgroud)

当我在调试器中运行它时,调用将va_arg( argList, float )返回垃圾值( 2.0, 1.77499998, -1.08420217e-019 ),而不是传入的值( 0.60f, 0.20f, 0.20f ).

我有什么想法我做错了吗?据我所知,我完全遵循规范.我一直在使用http://www.cplusplus.com/reference/cstdarg/作为参考.

joh*_*ohn 5

在可变参数函数中,float参数将转换为double.尝试

weightTotal += va_arg( argList, double );
Run Code Online (Sandbox Code Playgroud)