2

I have a C program that output values to stdout from measure. I use printf to display them and the format allows me to change the precision

 printf("Scan=%d S_0=%.5f S_1=%.5f S_2=%.5f S_3=%.5f", scanId, S0, S1, S2, S3);

My issue is that I have a lot of printing like this one and if I want to change the precision quickly I have to get on each one and change it. I was wondering if it was possible to use something like a #define to have it on a precise location and it will apply on each printf at compilation. I know it is not possible easily without recompile but I'm ok with that. I know something similar as I ask here in python is:

f"{s_0:.{prec}f}"
2
  • 1
    No quick or easy or global-defaulty way, no. If you want to you can say int prec = 5; printf("Scan=%d S_0=%.*f S_1=%.*f S_2=%.*f S_3=%.*f", scanId, prec, S0, prec, S1, prec, S2, prec, S3);, but that may be more trouble than it's worth. Commented Feb 9, 2022 at 23:30
  • Thank you, It looks heavy yes but that works. Commented Feb 9, 2022 at 23:33

2 Answers 2

7

You can use a * symbol in place of the precision, in which case the precision is given as a parameter. Then you can define a constant to pass to printf.

#define P_FLOAT 5

printf("Scan=%d S_0=%.*f S_1=%.*f S_2=%.*f S_3=%.*f", 
       scanId, P_FLOAT, S0, P_FLOAT, S1, P_FLOAT, S2, P_FLOAT, S3);
Sign up to request clarification or add additional context in comments.

Comments

6

One way would be to do a #define (as you guessed) like this:

#define PFLT "%.5f"

printf("Scan=%d S_0=" PFLT " S_1=" PFLT " S_2=" PFLT " S_3=" PFLT, scanId, S0, S1, S2, S3);

Then to change the precision you just need to alter the #define and recompile.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.