我正在迭代一個int數組來查找中值,然後返回中位數,這部分程序似乎工作。如何將一個int數組上的操作的結果轉換爲double?
但是,中位數必須轉換爲double
,它顯示的是小數位,但它沒有產生正確的輸出,爲什麼?
import java.util.*;
public class Example
{
public static void main(String[] args)
{
int[] exampleArray = {2, 5, 10, 19, 23, 34};
System.out.println("Median is: " + findMedian(exampleArray));
// The output produced here should be 14.5 not 14.0
}
public static double findMedian(final int[] tempArray)
{
int median = 0,
Index = tempArray.length/2;
if(tempArray.length % 2 == 1)
{
median = tempArray[Index];
/* I believe the problem is breaking down here I can't cast Index or
the tempArray to a double. I can copy the array elements into a new double array
but I tried that as well and the output was still off.
*/
}
else
median = (tempArray[Index] + tempArray[Index - 1])/2;
return (double)median;
}
}
哈,我甚至沒有考慮過,但它是有道理的謝謝你的迴應和解釋! – Afflicted