0
Why am I not getting average in decimal even after using float statement?
8 Respostas
+ 3
Where is the float statement? you should've cast the (a + b + c) into a float before division
average = (float)( a + b + c ) / 3;
+ 3
int = int / int
float = float / float
float = int / float
float = float/int
+ 3
The compiler works from right to left. First it evaluate the value of (a+b+c)/3. Since a+b+c and 3 are int, the value will evaluate as int. Then the int value will be stored in average. So you have to cast the value before assigning to average.
average is already a float type doesn't mean it will convert the int value to float. You have to type cast it seperately.
+ 3
Krs 7,
As an alternative, we can use a floating point literal as the RHS (right-hand-side) operand of the division operator /
average = ( a + b + c ) / 3.0;
Notice the RHS is 3.0 (a floating point literal) rather than 3 (an integer literal).
+ 2
Because <a>, <b> and <c> are all integers, integer division will take place when evaluating `( a + b + c ) / 3`.
By casting result of `( a + b + c )` as `float`, floating point division takes place instead.
+ 1
Ipang I have declared average as float. So why I have to add it again.
+ 1
Krs 7
Average is float not a, b, c and operation perform from right direction not from left direction so
(a + b + c) / 3 will give integer because all are of type integer so to get in float cast with float.
0
Because you are acquiring int insted of float