Is there a way to get the users input and then use that to decide what the precision of the outputted number should be?
What I mean is that I have a function to get the precision that the user wants and then I would want to be able to use that inputted number to decide how many decimal places should be shown. Normally when you are creating the program, you can decide it like this: printf("The number is: %0.2f", number);
, but can that %0.2f
also be dynamically changed so the user can decide if it should be 0.2, 0.3, 0.4, etc?
CodePudding user response:
can that
%0.2f
also be dynamically changed so the user can decide if it should be 0.2, 0.3, 0.4, etc?
Yes.
int prec = 2;
printf("The number is: %0.*f", prec, number);
Change prec
to be what you want at runtime.
CodePudding user response:
Read the user’s input as characters. Test whether the user’s input is in an acceptable form. Count the number of digits the user entered. (You might count either the total number of digits or just the number after the decimal point, if any, as you choose.) Then convert the recorded characters to floating-point (e.g., use the strtod
function).
When printing, using %.*f
to fix the number of digits after the decimal point or %#.*g
to fix the number of significant digits (total digits in the number from the first non-zero digit to the last non-zero digit). For either of these options, pass two arguments to printf
: first the number of digits and second the number to be printed.