0

if I use double sum=0 instead of int sum=0, I get the expected answer (38.8) but when I use int I get 38.0 as answer. I want to know why is this happening since my return type is double so I should not get automatically accurate decimal value output.

public class prg21 {

    public static  double average(int...ar)
{
    int sum=0;

    for(int x:ar)
    {
        sum+=x;
    }

    return sum/ar.length;
}
public static void main(String args[])
{
    int []arr= {5,77,2,65,45};
    System.out.println("Average="+average(arr));
}

}

I expect 38.8 but I get 38.0

Vincent Passau
  • 722
  • 8
  • 20
  • `return sum/(double)ar.length;`. What your are currently doing is returning the int result of `sum/ar.length` (which is round) casted to double by the return type. – Paul Lemarchand Jun 11 '19 at 19:04
  • I recommend you to learn about variables and what each one of them does – TehMattGR Jun 11 '19 at 19:07

1 Answers1

1

int datatype will drop any decimal value

you get 38.0 because the expression is saved into an int, dropping decimals and making it 38, then it's returned as a double so it's converted to 38.0

Artanis
  • 454
  • 4
  • 23