Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

E notation in C

I'm reading C Programming - A modern approach, and I have stumbled across the section about E-notation. I have difficulties to understand them.

Take the following code:

printf("%12.5e", 30.253);

This results to the following output:

3.02530e+01

Can someone explain how this works? What does the number 12 signify here?

like image 309
user500468 Avatar asked Dec 15 '22 14:12

user500468


1 Answers

The printf "%12.5e" format instructs printf to convert the double (or float) argument to a string in exponential notation with 5 digits after the . and a total of at least 12 characters. In your example, the output actually contains an extra space before the number: 3.02530e+01 to make for a total of 12 characters. To make it more obvious, you can try:

printf("|%12.5e|\n", 30.253);

And verify that the output is:

| 3.02530e+01|

Exponential notation produced by printf() always uses a single digit before the . and an exponent (e+01 here) representing the power of 10 by which to multiply the number. It is a notation commonly used in the scientific community:

30.12 is the same as 3.012e1 or 3.012e+01
0.0012 is the same as 1.2e-3

You can use this syntax to write floating point constants in your C source code.

like image 65
chqrlie Avatar answered Dec 30 '22 23:12

chqrlie