C program printing numbers with variable precision

Viewed 62

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;
}
2 Answers

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;
}

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

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