I'm wondering how I can use
scanf() to allow the user type in the number of decimal places he wants the answer given to, and how to input this variable into the
printf format specifier. For example
printf("The answer is %.(variable wanted here)f", answer);
Best How To :
If you use
* for your field precision specifier, it tells
printf that it is variable. You then specify an additional preceding
int argument to tell
printf the desired precision.
Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int.
Note that this also works to set the maximum number of characters to print from a string.
int places = 3;
printf("%0.*f\n", places, 1.23456789);
printf("%0.*f\n", places, 6.7);
char buf = "Stack OverflowXXXXXXXX";
printf("%.*s\n", 14, buf);