Reputation: 13
This function should pretty obviously return the minimum float value, but it always returns 0. While debugging, I found out that the va_arg()
function gets only that 31 right, then it gets some strange numbers, one of them every time being 0.
float var_min(int, float, ...);
void main()
{
cout << var_min(7, 31, 12, 4.5, 9, 22, 69, 8.21);
}
float var_min(int z, float, ...)
{
int i = 0;
float min, p;
va_list ap;
va_start(ap, z);
min = va_arg(ap, float);
for (i = 1; i < z; i++)
{
p = va_arg(ap, float);
min = (min < p) ? min : p;
}
va_end(ap);
return min;
}
Edit: this is the assignment:
Determine the minimum of a 10 float numbers from a string (implicit values or from the KB) using a function with a variable number of parameters. The first 7 values will be considered initially, next the last 3 and at the end these 2 values.
Upvotes: 0
Views: 245
Reputation: 223643
To use va_arg
starting with the second argument, change:
float var_min(int z, float, ...)
to:
float var_min(int z, ...)
(If there will always be at least one floating-point argument after z
, and you wish to include it in the parameter list, then give it a name, initialize min
from it directly, and change va_start(ap, z)
to use its name instead of z
.)
To pass float
or double
arguments to a variable-argument function, they must be explicitly of float
or double
type; integer types will not be converted to floating-point types, so:
var_min(7, 31, 12, 4.5, 9, 22, 69, 8.21);
should be:
var_min(7, 31., 12., 4.5, 9., 22., 69., 8.21);
In variable arguments, float
arguments are promoted to double
, so va_arg(ap, float)
should be va_arg(ap, double)
in both places it appears, and float min, p;
should be double min, p;
.
void main()
is not a standard declaration for main
. It could be int main()
.
Upvotes: 1