Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct format specifier for double in printf

What is the correct format specifier for double in printf? Is it %f or is it %lf? I believe it's %f, but I am not sure.

Code sample

#include <stdio.h>  int main() {    double d = 1.4;    printf("%lf", d); // Is this wrong? } 
like image 436
Leopard Avatar asked Nov 24 '10 06:11

Leopard


People also ask

Is %F for double?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

Is %d for double?

%d stands for decimal and it expects an argument of type int (or some smaller signed integer type that then gets promoted). Floating-point types float and double both get passed the same way (promoted to double ) and both of them use %f .


1 Answers

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).


1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.

like image 81
Jerry Coffin Avatar answered Sep 29 '22 16:09

Jerry Coffin