Can I create printf format plugins like C ++ streams

I am comparing the output of two programs, one C to another C ++ using diff , so the output should be identical.

Is there a way to printf a double so that it is formatted as if it were printed using << mydouble .

I am currently using printf("%g",mydouble)

Here are some examples of differences:

 c: 3.24769e-05 c++: 3.2477e-05 c: 0.0026572 c++: 0.00265721 

Interestingly, scientific notation has more digits in c, and decimal notation has more in C ++.

+7
printf cout
source share
1 answer

You can solve this problem using format specifiers in C.

For example, let's say that you want to print only three places after the decimal place, you can make your printf as follows:

 printf("%.3lf", dub); 

If the value is double dub = .0137; the output will be 0.014

This will fix the problem with your 2nd case if you want to print more precision that you could write:

 printf("%.8lf", dub); 

Your result for double dub = 0.00265721; will be then 0.00265721

The case for% g works in the same way, except for the number on the left, which is included in the calculation. If you want a C ++ version (the lower accuracy I assume), then your code will look like this:

 double dub = .0000324769; printf("%.5g", dub); 

What gives 3.2477e-05

+3
source share

All Articles