result of
printf("%d\n", 5.0 + 2);
is 0
but
int num = 5.0 + 2;
printf("%d\n", num);
is 7
What's the difference between the two?
%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 .
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.
Updated on April 27, 2019. The double is a fundamental data type built into the compiler and used to define numeric variables holding numbers with decimal points. C, C++, C# and many other programming languages recognize the double as a type. A double type can represent fractional as well as whole values.
When you do 1/2 that is integer division because two operands are integers, hence it resolves to zero (0.5 rounded down to zero). If you convert any one of them to double, you'll get a double result. Show activity on this post. 1 and 2 are both integers, so 1 / 2 == 0 .
The result of 5.0 + 2
is 7.0
and is of type double
.
The "%d"
format is to print int
.
Mismatching format specification and argument type leads to undefined behavior.
To print a float
or double
value with printf
you should use the format "%f"
.
With
int num = 5.0 + 2;
you convert the result of 5.0 + 2
into the int
value 7
. Then you print the int
value using the correct format specifier.
In all expressions, every operand has a type. 5.0
has type double
. 2
has type int
.
Whenever a double and an integer are used as operands of the same operator, the integer is silently converted to a double before calculation. The result is of type double
.
And so you pass double
to printf
, but you have told it to expect an int
, since you used %d
. The result is a bug, the outcome is not defined.
But in case of int num = 5.0 + 2;
, you first get a result as double
, 7.0
. Then force a conversion back to int
. That code is equivalent to:
int num = (int)((double)5.0 + (double)2);
More details here: Implicit type promotion rules
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