You're dividing by 3
, which is an integer. You should cast one of the two operands to float, or divide by 3.0f
. Examples:
(float) (a + b + c) / 3; // cast operator has the precedence over division operator
(a + b + c) / (float) 3;
(a + b + c) / 3.0f;
From the Current C Programming Language Standard – ISO/IEC 9899:2018 (C18), you can read that When integers are divided, the result of the /
operator is the algebraic quotient with any fractional part discarded:
6.5.5 Multiplicative operators
Syntax
1 multiplicative-expression:
cast-expression
multiplicative-expression *
cast-expression
multiplicative-expression /
cast-expression
multiplicative-expression %
cast-expression
Constraints
2 Each of the operands shall have arithmetic type. The operands of the %
operator shall have integer
type.
Semantics
3 The usual arithmetic conversions are performed on the operands.
4 The result of the binary *
operator is the product of the operands.
5 The result of the /
operator is the quotient from the division of the first operand by the second; the
result of the %
operator is the remainder. In both operations, if the value of the second operand is
zero, the behavior is undefined.
6 When integers are divided, the result of the /
operator is the algebraic quotient with any fractional
part discarded.109) If the quotient a/b
is representable, the expression (a/b)*b + a%b
shall equal a
;
otherwise, the behavior of both a/b
and a%b
is undefined.