what if my x value comes from a scanf? How can I do so that when I print it it doesn't get rounded down or up?
scanf
with an %f
directive will read the input and convert it to a float
(not a double
). If the matched text does not correspond to a number exactly representable as a float
then there will be rounding at this stage. There is no alternative.
When you pass an argument of type float to printf()
for printing, it will be promoted to type double
. This is required by the signature of that function. But type double
can exactly represent all values of type float
, so this promotion does not involve any rounding. printf
's handling of the %f
directives is aligned with this automatic promotion: the corresponding (promoted) argument is expected to be of type double
.
There are multiple avenues to reproducing the input exactly, depending on what constraints you are willing to put on that input. The most general is to read, store, and print the data as a string, though even this has its complications.
If you are willing to place a limit on the maximum decimal range and precision for which verbatim reproduction is supported, then you may be able to get output rounded to the same representation as the input by specifying a precision in your printf
field directives:
float f;
scanf("%f", &f);
printf("%f %.2f %5.2f\n", f, f, f);
If you want to use a built-in floating-point format and also avoid trailing zeroes being appended then either an explicit precision like that or a %g
directive is probably needed:
printf("%f %g\n", f, f);
Other alternatives are more involved, such as creating a fixed-point or arbitrary-precision decimal data type, along with appropriate functions for reading and writing it. I presume that goes beyond what you're presently interested in doing.
Note: "double" is short for "double precision", as opposed to notionally single-precision "float". The former is the larger type in terms of storage and representational capability. In real-world implementations, there is never any "rounding down" from float
to double
.