Home > Enterprise >  C program printing numbers with variable precision
C program printing numbers with variable precision

Time:01-15

Do you know how a number can be rounded up and printed with a precision that is not fixed by some natural number, but by some variable? If the user needs to enter how many decimal places to round, how to solve it?

#include <stdio.h>
int main()
{
int r;
double var = 37.66666;
scanf("%d", &r);
printf("%.2f", var);
return 0;
}

CodePudding user response:

Here's simple approach that would work in your case:
You just need to put * before f, and that's it.

#include <stdio.h>
int main()
{
int r;
double var = 37.66666;
scanf("%d", &r);
printf("%.*f",r, var);
return 0;
}

CodePudding user response:

You can put a * in place of the precision, in which case you can specify an int as the precision.

printf("%.*f", r, var);
  •  Tags:  
  • Related