-1

Consider the following code snippet:

    int[] dataSet = {1,2,3,4};
    int total = 0;
    for(int temp : dataSet){
        total += temp;
}

    double mean = (total / dataSet.length);
    System.out.println(mean);

I expected this to output 2.5, as that is the mean of 1,2,3,4. Instead, it printed 2.0. Why is this and how can I fix it?

Sidharth D
  • 39
  • 1
  • 2
  • 13

1 Answers1

0

Java 7 or more if you use a int / int you have a int

Try to cast one number to double.

double res = 1 / (double) 2;