0

In the following:

float n1= 3.0;
double n2 = 3.0;
long n3 = 2000000000L;
long n4 = 1234567890L;
printf("%f %Lf %ld %ld\n", n1, n2, n3, n4);

3.000000 1.200000 2000000000 1234567890

Why is 1.2 printed for the second value and not 3.0? I suppose maybe I'm screwing up the float prints -- with float, double, and long double, or what's the reason why the above prints an incorrect result? Is this the correct way to print all decimal-types?

float n1= 3.0F;
double n2 = 3.0;
long double n3 = 3.0L;
printf("%f %f %Lf\n", n1, n2, n3);
carl.hiass
  • 1,526
  • 1
  • 6
  • 26

1 Answers1

4

Becaue %Lf isn't the specifier for double, it's the specifier for long double. float promotes to double automatically; hence %f covers both float and double. But long double needs its own.

You kinda got lucky here. On some platforms, the rest of the arguments would be misaligned.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • are all non-qualified decimal literals parsed as `double` ? For example, if I enter in 2.0, would that be `double` unless doing `2.0L` (long) or `2.0F` (float) ? – carl.hiass Jan 16 '21 at 21:27
  • @carl.hiass: The rule in play is you passed a `float` as an argument to a variadic function. There are no vardiac floats. 2.0 would be a float in a context that allowed it to be. – Joshua Jan 16 '21 at 21:34
  • ok, but when I enter a decimal literal in VS Code it displays it as a `double` unless I qualify it. For example: https://gyazo.com/e78a218fdcd29c240019b8ff4038e11a – carl.hiass Jan 16 '21 at 21:37
  • 1
    @carl.hiass: A difference that makes no difference. On all modern platforms, all floating point arithmetic is done by casting all arguments to long double, performing the calculation, and casting them back. – Joshua Jan 16 '21 at 21:39
  • @Joshua, pretty sure that not all modern platforms cast to long double, given that some do have higher precision long doubles than doubles, and the cost of those higher precision operations can be substantially higher than doubles, in terms of power consumption, memory/registers and execution time. Think IoT. Your statement is likely true for most PC's and Servers. – jwdonahue Jan 16 '21 at 22:07
  • @jwdonahue: I've seen some for which long double was just double if that's what you mean. – Joshua Jan 16 '21 at 22:22
  • @Joshua, well that too, but there are systems that don't even have floating point coprocessors or built-in operations, so when you are forced to do some float-ops, you have to rely on software implementations, where gratuitous casting to higher precision would be a firing offense. – jwdonahue Jan 16 '21 at 22:27