1

Im trying to print out a format of lets say x levels of accuracy meaning it should print if x = 10

float foo;
printf("levels of accuracy %.10f", foo);

What i've tried: I already have the math to convert the x to the desired decimal place. something like..

int multiplier = 10;
float initialaccuracy = 1.0;
float threshold = initialaccuracy / ((float)(pow(multiplier, accuracy)));

What I want to know:

How do i use the format of that x into the printf so if i pick x= 4 it would be %.4f or if i pick 15 it would be %.15f, without hardcoding those values just using it of whatever i pass in?

2 Answers2

3

You can put a * in place of the precision specifier and pass it as a separate parameter:

int accuracy = 10;
printf("levels of accuracy %.*f", accuracy, foo);
dbush
  • 205,898
  • 23
  • 218
  • 273
0

Or, build your format string 'on the fly'...

char fmt[99];
sprintf(fmt,"levels of accuracy %%.%df",accuracy);
printf(fmt,foo);
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42
  • The first seemed a bit easier to understand but I appreciate the response. Ima look into sprintf haven’t used it yet. –  Oct 03 '19 at 04:12