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!
sum
andMemory.size()
are both integers, the calculation is carried out using integer arithmetic, and then cast to afloat
to be returned