-4

When I run the code below

int main(int argc,char *argv[]) {
    double n = 2E-1;
    printf("%d",n);
}

When I run the code it prints a weird number instead of 0.2(2E-1).

k0na
  • 9
  • 1
  • 2
  • 5
    `"%f"` is the correct format specifier to print a `double`. – mch Jan 21 '19 at 15:33
  • 1
    It's the [E-Notation](https://en.wikipedia.org/wiki/Scientific_notation#E-notation). `E` is not a constant. – Eugene Sh. Jan 21 '19 at 15:33
  • Possibly - I'm not sure which part (the exponential notation or the printing) is more important to OP. – Useless Jan 21 '19 at 15:41
  • [What does the numerical literal 0.e0f mean?](https://stackoverflow.com/q/24777846/995714), [How is the 'E/e' in hexadecimal differentiated from the 'E/e' in exponential form in a hexadecimal floating point literal?](https://stackoverflow.com/q/38412560/995714). And your code above almost definitely doesn't produce 0.2 or 2e-1, since you're printing a double with `%d` – phuclv Jan 21 '19 at 15:53
  • @k0na What compiler are you using that does not warn about `double n = ...; printf("%d",n);`? – chux - Reinstate Monica Jan 21 '19 at 16:53

2 Answers2

5

What does the constant E do in the c language

The documentation for floating-point constants is here.

The form 1e2 or 1E2 means 1 times ten to the power of 2, and you're perfectly correct that 2E-1 means 2 times ten to the power of -1, or 0.2.

It's based on the scientific E notation linked by Eugene.

When I run the code it prints a weird number

That's just because you used the wrong format specifier. These are documented here, and you can see you should use one of eEfFgG for doubles.

Useless
  • 64,155
  • 6
  • 88
  • 132
0

In C language, for double, the format specifier is %lf

So, if you use %lf then it will print n as 0.200000

And if you use %g or %G (as supported data types are float, double) then the output will be 0.2

brunorey
  • 2,135
  • 1
  • 18
  • 26