I there.
I'm learning C and I have this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double buyval, deliveredval, change;
printf("What's the buy value? ");
scanf("%lf", &buyval);
do{
printf("What's the value delivered? ");
scanf("%lf", &deliveredval);
if (deliveredval < buyval){
printf("Delivered value must be greater then buy value \n\n");
}
} while (deliveredval < buyval);
change = deliveredval - buyval;
printf("Change is %4.2lf", change);
return 0;
}
With this code, the last print is always 0.00 but is I change
printf("Change is %4.2lf", change);
to
printf("Change is %4.2f", change);
It works as expected. Why is that? Doubles aren't formatted as lf?
"%f"
is for double
s (and float
s which are converted to double
automagically); %Lf
is for long double
s.
You can read all about printf
specifiers in the C99 Standard (or in PDF).
The l
in the format specifier "%lf"
has no effect: "%lf"
(the same as "%f"
) is to print double
s.
Your result should be the same with any sane C99 compiler / implementation.
According to my documents, in C89, "%lf"
is an invalid format specifier; and if you are using a C89 compiler / implementation, it's Undefined Behaviour the use it.
Note that the rules for scanf
are a bit different.
In variable argument lists, float
values are automatically converted to double
; char
and short
to int
. Therefore, printf
needs only %f
for double
values (to which float values are converted to).
Pointers are not converted - this would not make much sense. This is the reason, why scanf
needs to distinguish between %f
for float
targets and %lf
for double
targets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With