ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Hi,
I am writing a tool that needs to print doubles as exponential number with a certain precision and such.
I am using the %E modifier with the right precision (*.14), but my requirements need the number of digits after the E to be 3. Valid output example:
-9.00000000000000E-002
However, I can only get two digits after the E symbol... This is what I am doing right now:
double d = 1.232;
printf("double: %+.14E\n", d);
This prints as: +1.23200000000000E+00.
Thank you in advance for suggestions that may help!
Acording to "The C Programming Language" the E gives formatted output in this form ill retype what it says
Quote:
e,E double; [-]m.dddddde+/-xx or [-]m.ddddddE+/-xx, where the number of d's is given by the precision (default 6)
Thus I would surmize that printing output in the way that you need is not auto built into the printf function. You with either have to do 1 of 2 things.
1. Look around for a print function written in another library to do what you want.
2. Write a new printf (possibly from the printf source) that can output in the way that you want.
#include <math.h>
#include <stdio.h>
#include <stdlib.h> // for `int abs(int)'
main()
{
double x = -1.1500018e18;
int ex = log10( fabs(x) );
double mantissa = (x/pow(10.0, ex));
printf("x=%+.14fe%c%.3d\n", mantissa, (ex<0)?'-':'+', abs(ex));
}
You have to compile this with -lm flag:
Code:
gcc num.c -lm
WARNING: I strongly recommend you to not use this approach in scientific software!
It's: a) very inefficient, b) may cause overflows and loosing of accuracy, c)maybe smth. else.
Fortran seems more flexible, allowing you to specify the width of the exponent field. If you can arrange to call a Fortran routine from C, you might save yourself some trouble. For example, g77 on this code:
Code:
program main
d = 1.232
x = -1.1500018e18
write(6,9), d, x
9 format( "d = ", e14.6e3, " x = ", e20.10e4 )
end
produces this:
Code:
% ./a.out
d = 0.123200E+001 x = -0.1150001820E+0019
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.