Reputation: 49
void main()
{
printf("%f",12/7.0);
getch();
}
Will the type conversion take place in this code and if yes then why it is taking place and if no why it is not taking place in this code please explain? Also I think 7.0 which is of double data type here (according to rule of type conversion) and 12 which is of integer data type would give data type double but when I print with %lf then the output on screen is again float I don't know how please correct me ?
Upvotes: 0
Views: 62
Reputation: 36391
You can't deduce the type of the expression by the result of the printing. printf
may show you only part of the value...
man printf
says for f
or F
format (emphasize is mine):
fF
The double argument is rounded and converted to decimal notation in the style
[-]ddd.ddd
, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal- point character appears. If a decimal point appears, at least one digit appears before it.
12 is an int
literal, 7.0
is a double
literal. By the rules of expression evaluation int
will be promoted to double
and the result will be a double
that is printed according to the format (f
is not for float
but for double
).
If you want to print the value computed by a float
division, you need to restrict to float
using:
12/7.0f
The result will be float
, and you may ask why do I use a double
specifier then? Because, in any variadic function every float
will be promoted to double
. As printf
is a variadic function...
This is why there is no float
specifier in format string of printf
.
Upvotes: 2