[英]Why does this code report that -31 is greater than 6?
I have a function double max(int count, ...)
in my program.我的程序中有一个函数
double max(int count, ...)
。 This function should return the highest number, but it reports that -31 > 6
.这个函数应该返回最大的数字,但它报告
-31 > 6
。 Where is my mistake?我的错误在哪里? I'm trying to learn
va_
.我正在努力学习
va_
。 How can I fix this?我怎样才能解决这个问题?
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;
}
You are invoking undefined behavior .您正在调用未定义的行为。 You are not passing in
double
values to max()
, you are passing in int
values instead.您没有将
double
值传递给max()
,而是在传递int
值。 int
and double
are different sizes in memory, and va_arg()
can't read an int
parameter as if it were a double
, and vice versa. int
和double
在内存中的大小不同,并且va_arg()
无法读取int
参数,就好像它是double
一样,反之亦然。 You need to match the types correctly.您需要正确匹配类型。
In this example, change all of the double
s to int
s, eg:在此示例中,将所有
double
s 更改为int
s,例如:
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;
}
Otherwise, change the int
s to double
s instead, eg:否则,将
int
s 改为double
s,例如:
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;
}
Either way, you might consider a slight change in logic in how you are handling the max
value.无论哪种方式,您都可以考虑在处理
max
的逻辑上稍作改变。 You should initialize it to the 1st value that is passed in, eg:您应该将其初始化为传入的第一个值,例如:
<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;
}
Also, note that all of the above is the C way of handling things.另外,请注意,以上所有内容都是 C 处理事物的方式。 But you also tagged your question as C++, and the C++ way to handle this would be to use a variadic template instead of ellipses (ie, no
va_arg()
needed), or else take a std::initializer_list
or at least a pair of iterator
s so that you can then make use of the standard std::max_element()
algorithm.但是您还将您的问题标记为 C++,处理此问题的 C++ 方法是使用可变参数模板而不是省略号(即不需要
va_arg()
),或者采用std::initializer_list
或至少一对iterator
s,以便您可以使用标准的std::max_element()
算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.