In an article on the w3resource.com, I've seen the following code:
double x, y;
pr1 = sqrt(pr1);
x = (-b + pr1)/(2*a);
y = (-b - pr1)/(2*a);
printf("Root1 = %.5lf\n", x);
printf("Root1 = %.5lf\n", y);
The article says to take three floating-point numbers. But in their solution (this code snippet), they have used the %lf format specifier.
Why have they used %lf instead of %f?
Can I also use %f instead of %lf for floating-point numbers?
If I use a float keyword instead of double, and use %f, is there any issue?
The output is the same for me.
%fhas different meaning inprintfandscanffamily functions:printf,%fand%lfare equivalent, and both are matched bydouble. This is because in variadic functions, allfloatarguments are promoted todoublewhen the function is called, so there is no difference between passingfloatanddoubleat a language level.scanf,%fmatches afloat*and%lfmatches adouble*, and this distinction is very important. Using the wrong type of pointer will result in undefined behavior.You can also use cdecl+ to better understand
printfandscanfcalls. The output is as follows:When in doubt, use
%fforfloatand%lffordouble, even inprintf, where there is no difference between the two. You will introduce pointless inconsistencies between yourscanfandprintfformat strings otherwise.Note on floating-point numbers
You may have gotten confused by the meaning of
floatand floating-point number.float,double,long double, and more are floating-point numbers in C. When the article says floating-point number, they could also meandouble,_Decimal32,_Float128, etc.Why doesn't
scanfpromotefloat*todouble*similar toprintf?This is not possible, because the object in which we're storing the
floatcannot be used to store adouble.doublein afloatwhich consists of four bytes, which is impossible.