- Everything in C has a type, including constants like
7
which is type int
, 7.0f
which is type float
or 7.0
which is type double
.
- Whenever mixing fixed point and floating point operands in the same operation with two operands (generally a bad idea), then the fixed point operand is converted to floating point. This is called "the usual arithmetic conversions".
Examples:
int input;
, input / 7
. Both operands are int
, no promotion occurs, the result will be of type int
. This has everything to do with the /
operator and nothing to do with where you place the result. The divison will get carried out on int
type, so if you wanted it to be type float
, it's already too late. Something like float f = input / 7
will not affect the type used by the division in any way. It will only convert the resulting int
to float
.
int input;
, input / 7.0f
. One operand is type int
, the other is type float
. The usual arithmetic conversions state that the int
operand will get converted to float
before the division. So this would solve the problem.
However, here is a better idea: Simply never mix fixed point and floating point in the same expression, because the potential for bugs is huge. Instead do this:
scanf("%d", &input);
float f_input = (float)input;
printf("Output: %f", (f_input / 7.0f);
Now nothing goes on implicitly, all implicit conversions have been removed. The cast is not necessary, but creates self-documenting code saying: "yes I do mean to make this a float type rather than had it happen by chance/accident".
(Advanced topic detail: printf
actually converts the passed float
to double
, but we need not worry about that.)