K
Keith Thompson
CBFalconer said:You seem to have a faulty compiler. size_t is an unsigned integral
value, picked so as to be able to describe all sizes. Not a
double, which is signed and floating point. I assume n is
integral.
The warning is correct. It complains of a double *format*, namely
the "%f".
If the "%d" is correct, then n must be of type int. We know len
is of type size_t, so len / n is most likely of type size_t as well.
I note that in some languages other than C, ``x / y'', where x and
y are integers, yields a floating-point result. In C, it yields
an integer.
If you want a floating-point ratio, you can convert the operands
before dividing:
printf("There were %d lines, average length %f\n",
n, (double)len / (double)n);
(Only one of the two casts is really necessary, but I like the
symmetry.)
Note that this:
(double)(len / n)
converts the result of the integral division, and doesn't give you
the fractional result you might expect. For example, (double)3 / 2
is 1.5, but (double)(3 / 2) is 1.0.
With C99 I believe the printf format for size_t is x (assuming a
C99 library). For C90, cast the value to long and print a long.
Why guess? The C99 printf format for size_t is "%zu". For C90, it's
better to cast to unsigned long rather than long (and use "%lu").