0

I'm having some trouble trying to make a GetAverage() function in Java:

ArrayList<Integer> Memory = new ArrayList<Integer>();

public float Average(){
    int sum = 0;
    for(int value : Memory){
        sum += value;
    }
    float average = sum / Memory.size();
    return average;
}

If there's something inside the Arraylist like: {1, 1, 1, 3, 3, 3}

The result of the Average() should be 2.5 but returns 2.0

I've looked how to fix this issue, but still nothing have worked. There's some examples I've seen that use:

float example = 15.4f;

But I'm not initializing a floating variable with a predefined value, I'm initializing a float variable with the result of an operation.

Thanks in advance!

  • See this question: https://stackoverflow.com/questions/787700/how-to-make-the-division-of-2-ints-produce-a-float-instead-of-another-int – Johan Nordlinder Apr 14 '22 at 04:26
  • [Odd behaviors when dividing doubles in Java](https://stackoverflow.com/q/13668007/995714) – phuclv Apr 14 '22 at 04:26
  • More technically, because `sum` and `Memory.size()` are both integers, the calculation is carried out using integer arithmetic, and then cast to a `float` to be returned – jr593 Apr 14 '22 at 07:01

0 Answers0