0

Why am I not getting average in decimal even after using float statement?

https://code.sololearn.com/chKb5Aj3x2Y3/?ref=app

7th Oct 2021, 7:14 AM
King
King - avatar
8 Réponses
+ 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;
7th Oct 2021, 7:32 AM
Ipang
+ 3
int = int / int float = float / float float = int / float float = float/int
7th Oct 2021, 7:38 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
+ 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.
7th Oct 2021, 8:30 AM
Arun Ruban SJ
Arun Ruban SJ - avatar
+ 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).
7th Oct 2021, 8:37 AM
Ipang
+ 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.
7th Oct 2021, 8:27 AM
Ipang
+ 1
Ipang I have declared average as float. So why I have to add it again.
7th Oct 2021, 8:23 AM
King
King - avatar
+ 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.
7th Oct 2021, 8:53 AM
A͢J
A͢J - avatar
0
Because you are acquiring int insted of float
8th Oct 2021, 5:51 PM
Rishav Kumar
Rishav Kumar - avatar