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);
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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: 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.
ok, but when I enter a decimal literal in VS Code it displays it as a double unless I qualify it. For example: gyazo.com/e78a218fdcd29c240019b8ff4038e11a
@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, 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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.