1

I wanted to create a function that would print my array of doubles using a specified floating point precision as an argument to the function. Let's say i have the following code:

void printDoubleArrayPrecision(int length, double *arr, int precision) {
    printf("[");
    if (length > 0) {
        printf("%.2lf", arr[0]);
        for (int i = 1; i < length; i++) {
            printf(",%.2lf", arr[i]);
        }
    }
    printf("]\n");
}

Is there any way of replacing the 2 in printf(",%.2lf", arr[i]); with the given argument precision?

Cornul11
  • 191
  • 1
  • 12

2 Answers2

2

There is actually a possibility in printf:

printf("%.*lf", precision, arr[i]);

will print arr[i] with the given precision.

Osiris
  • 2,783
  • 9
  • 17
1

Apparently i should've searched for my solution by looking for printing strings with variable length instead of doubles. A solution for my question would be:

printf(",%.*lf", precision, arr[i]);
Cornul11
  • 191
  • 1
  • 12