Reputation: 11
The following is a sample prog
#include<stdio.h>
#include<math.h>
main()
{
int x;
scanf("%d",&x);
printf("%.2f\n",(1/pow(2,x)));
}
Here I give .2f for floating point formatting. We can also give respective .3f or .5f etc according to requirement.
Suppose we do not know till what decimal after the '.' it is to be printed. I want to give something like a value n through input, so that it prints decimals till the n.
like .nf if n = 5 and x =1, it prints 0.50000 and for n = 3 it should print 0.500
How do I achieve this?
Upvotes: 0
Views: 77
Reputation: 123448
You can specify the desired precision as a variable:
int n = 5;
printf("%.*f\n", n, (1.0/pow(2,x))); /* equivalent to %.5f */
Quoting from man 3 printf
:
An optional precision, in the form of a period ('.') followed by an
optional decimal digit string. Instead of a decimal digit string one
may write "*" or "*m$" (for some decimal integer m) to specify that the
precision is given in the next argument, or in the m-th argument,
respectively, which must be of type int.
Upvotes: 8