Reputation: 31
I want to print n
number of digits after decimal while printing a number of datatype double
. However, integer n
must be obtained from user using scanf()
.
double pi = acos(-1);
int n;
printf("\nEnter the number of decimal digits required : ");
scanf("%d",&n);
Now, how to use printf()
to print n
number of decimal digits of pi?
Upvotes: 2
Views: 98
Reputation: 134396
Quoting C11
, chapter §7.21.6.1/p4, for the precision option,
Each conversion specification is introduced by the character
%
. After the%
, the following appear in sequence:
- An optional precision that gives [...] the number of digits to appear after the decimal-point character for
a
,A
,e
,E
,f
, andF
conversions, [...] The precision takes the form of a period (.
) followed either by an asterisk*
(described later) or by an optional decimal integer; [...]
and, in paragraph 5,
As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. [...]
So, you can use the format
printf("%.*f", precision, variable);
like
printf("%.*f", n, pi);
to use the precision n
taken from user.
Upvotes: 5