1 / 2
is not a floating-point expression.
printf("%f", ( 1 / 2 ) );
The inner parentheses are unnecessary; this is a bit easier to read as:
printf("%f", 1 / 2);
In most cases, the type of an expression in C is determined by the expression itself, not by the context in which it appears. This applies even to subexpressions of larger expressions.
The arithmetic operators +
, -
, *
, and /
always take two operands of the same numeric type, and yield a result of that type. There are rules to convert the operands to a common type, but 1
and 2
are both of type int
, so we needn't worry about that. All these operators, if invoked with int
operands, yield an int
result. Integer division truncates, discarding any remainder, so 1 / 2
yields the int
value 0
.
So the above is equivalent to:
printf("%f", 0);
The "%f"
format requires an argument of type double
; 0
is of type int
. For most functions, there would be an implicit conversion, but the types of the parameters are determined by the format string, not by the function declaration, so the compiler doesn't know what type to convert to. (Consider that the format string doesn't have to be a string literal.) Passing an int
argument with a "%f"
format has undefined behavior. In your case, it just happened to print 0
. We could speculate about how that happened, but it doesn't matter; you need to fix the code.
If you wanted to print that int
value, you could use "%d"
:
printf("%d", 1 / 2);
But you probably want 0.5
. You can get that by using operands of type double
:
printf("%f", 1.0 / 2.0);
(You could change just one of the two operands to a floating-point constant, but it's clearer to change both.)
Finally, you should print a newline at the end of your output:
printf("%f\n", 1.0 / 2.0);