为什么此代码报告 -31 大于 6?

Cih*_*han 0 c c++

double max(int count, ...)我的程序中有一个函数。此函数应返回最大数字,但它报告-31 > 6. 我的错误在哪里?我正在尝试学习va_。我怎样才能解决这个问题?

double max(int count, ...)
{
    double max = INT_MIN, test;

    int i;
    va_list values;
    va_start(values, count);
    for (i = 0; i < count; ++i)
    {
        test = va_arg(values, double);
        if (test > max)
        {
            max = test;
        }
    }
    va_end(values);
    return max;
}

int main()
{
    printf("%ld", max(5, 1, 6, -31, 23, 24));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 12

您正在调用未定义的行为。您不是double将值传递给max(),而是传递int值。 intdouble在内存中的大小不同,并且va_arg()无法int像读取参数一样读取参数double,反之亦然。您需要正确匹配类型。

在本例中,将所有doubles 更改为ints,例如:

int max(int count, ...)
{
    int max = INT_MIN, test;

    va_list values;
    va_start(values, count);
    for(int i = 0; i < count; ++i)
    {
        test = va_arg(values, int);
        if(test > max)
        {
            max = test;
        }
    }
    va_end(values);
    return max;
}

int main()
{
    printf("%d", max(5,1,6,-31,23,24));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在线演示

否则,将ints改为doubles,例如:

double max(int count, ...)
{
    double max = -DBL_MAX, test;

    va_list values;
    va_start(values, count);
    for(int i = 0; i < count; ++i)
    {
        test = va_arg(values, double);
        if(test > max)
        {
            max = test;
        }
    }
    va_end(values);
    return max;
}

int main()
{
    printf("%lf", max(5,1.0,6.0,-31.0,23.0,24.0));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在线演示


无论哪种方式,您都可以考虑在处理该max值的方式上稍微改变逻辑。您应该将其初始化为传入的第一个值,例如:

<type> max(int count, ...)
{
    if (count <= 0)
        return <default value>;

    va_list values;
    va_start(values, count);

    <type> max = va_arg(values, <type>), test;

    for(int i = 1; i < count; ++i)
    {
        test = va_arg(values, <type>);
        if (test > max)
        {
            max = test;
        }
    }

    va_end(values);
    return max;
}
Run Code Online (Sandbox Code Playgroud)

另外,请注意,以上所有内容都是 C 处理方式。但是您也将您的问题标记为 C++,处理此问题的 C++ 方法是使用可变参数模板而不是省略号(即,不需要va_arg()),或者采用一个std::initializer_list或至少一对iterators,以便您可以使用标准std::max_element()算法。