Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make printf format floats like C++ streams

Tags:

printf

cout

I am comparing the output of two programs, one C the other C++, using diff, so the output must be identical.

Is there any way to printf a double so that it is formatted as though it was printed using << mydouble.

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

Here are some examples of the differences:

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

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

like image 619
jsj Avatar asked Jan 13 '14 06:01

jsj


People also ask

Can we use printf in C++?

The C++ printf() function is usually used in C programming but can also run in C++.


1 Answers

You can solve this by using the format specifiers in C.

For example, say you would like to print out only 3 places after the decimal, you could make your printf like so:

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

With a value of double dub = .0137; the output would be 0.014

This would fix the issue with your 2nd case if you want more precision printed you could write:

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

Your output for double dub = 0.00265721; would then be 0.00265721

The case for %g works the same way except the number on the left is included in the calculation. If you wanted the C++ version (the lesser precision I assume) then your code would look like this:

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

Which yields 3.2477e-05

like image 96
Lucas Derraugh Avatar answered Oct 11 '22 10:10

Lucas Derraugh