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 fordoubles (andfloats which are converted todoubleautomagically);%Lfis forlong doubles.You can read all about
printfspecifiers in the C99 Standard (or in PDF).The
lin the format specifier"%lf"has no effect:"%lf"(the same as"%f") is to printdoubles.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
scanfare a bit different.