3.142857 is the area should be the output. but it is showing 3.000000 is the area
You might be thinking because you have a float
data type on the left-hand side of your assignment operator, the computation on the right-side
of your assignment operator should be a float computation.
However, C
programming language won't promote the variables to float
implicitly. It will do integer division and multiplication and after computing the result, the result (which will be an integer) will be implicitly casted to the data type on the LHS of your assignment operator (i.e., float).
To learn more about integer division, check this link. It says:
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is re-presentable, the expression (a/b)*b + a%b shall equal a.
So, you were getting 3.0000
because according to integer division, 22/7
is 3
(fractional part discarded) and after multiplying with a
twice, you will get an integer of value 3
. To assign the computed value of the expression to your variable c
, language does the implicit conversion to float having a value of 3.000
.
To solve your problem, you need to explicitly use variables or constants of type float
on RHS of your assignment operator or you can use explicit casting operator.
float c = 22.0f / 7 * a * a;
Because of higher associativity of division operator, (22.0 / 7)
will be calculated first and their result will be a float as one of operand (22.0
and 7
) is a float constant. Then, the result of the expression will be calculated and integer
operand will be promoted to float
data type. At the last, your result (which is float) will be assigned to your variable c
.
See this link to learn about the difference between 22.0
and 22.0f
.