I want to print out a float with a user-defined precision after decimal point in C, like say,

int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);

Then print the number no with dec decimal places.

有帮助吗?

解决方案 2

Do

int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);
printf("%.*f",dec,no);

其他提示

You may format the printing of a floating point number, but not its actual size.

You may read this on formatting floating point number.

To save your time, you may use the %f format specifier, as

printf("%.PRECISIONf", fvar);

where PRECISION is the number of digits you want after decimal, for e.g.

int 
print_float(float fvar, unsigned int precision) {
  char fs[32];
  sprintf(fs,"%%.%df", precision);
  return printf(fs, fvar);
}

On calling the routine:

print_float(2.0f, 2);

you will get 2.00 as the output.

Hope this solves your issue.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top