Can I make printf format floats like C++ streams

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++.


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

链接地址: http://www.djcxy.com/p/18570.html

上一篇: LeftNavBar在活动的顶部创建黑条

下一篇: 我可以制作像C ++流一样的printf格式文件吗?