I need help with a piece of code I’m writing. I want to compute the median of an array. Initially the types were all ints and it compouted the median with integer division which gave me a wrong answer. I changed everything to doubles but I’m getting a type mismatch error saying I can’t convert doubles to ints which doesn’t really make sense. Can someone help. This is my code:
public class MedianTest {
public static void main(String[] args) {
double median = 0;
double myValues[] = { 1, 2, 3, 4 };
double arrayHalfOdd = ((myValues.length - 1) / 2) + 1;
double arrayHalfEven = ((myValues.length - 1) / 2);
if ((myValues.length - 1) % 2 == 0) {
median = (myValues[arrayHalfEven] + myValues[arrayHalfEven + 1]) / 2;
} else {
median = myValues[arrayHalfOdd];
}
System.out.print(median);
}
}
the errors are in the myValues[arrayHalfEven] and myValues[arrayHalfOdd]
By the way this IS NOT homework
final answer: