我想调用此方法从数组中获取中值。该方法声明为public double getMedian(double[]list){//code}
。
我尝试将方法调用为getMedian(double,list)
,但我收到了错误消息。调用该方法的正确方法是什么?
这是完整的方法:
public double getMedian(double[] list) {
// calculate the length of the entries
// create an iterator
int factor = list.length - 1;
double[] first = new double[(int) ((double) factor / 2)];
double[] last = new double[first.length];
double[] middleNumbers = new double[1];
for (int i = 0; i < first.length; i++) {
first[i] = list[i];
}
for (int i = list.length; i > last.length; i--) {
last[i] = list[i];
}
for (int i = 0; i <= list.length; i++) {
if (list[i] != first[i] || list[i] != last[i])
middleNumbers[i] = list[i];
}
if (list.length % 2 == 0) {
double total = middleNumbers[0] + middleNumbers[1];
return total / 2;
} else {
System.out.println(middleNumbers);
return middleNumbers[0];
}
}
答案 0 :(得分:1)
该方法将double值数组作为参数。您可能希望创建一个double数组并传递:
double[] values = {0.1d, 0.3d, 0.5d, 1.0d, 1200.0d};
double median = this.getMedian(values); // should return 0.5d
但是getMedian
方法有一些逻辑错误阻止它正常工作。特别是,第二个循环开始超出数组的范围:
for (int i = list.length; i > last.length; i--) {
last[i] = list[i];
}
使用我的测试数据,i
从5
开始,倒计时直到i
大于5
,但该数组只包含从{{1}开始索引的元素} 0
。
答案 1 :(得分:0)
它只需要一个double,list就是你刚刚创建的数组名称。你需要做
getMedian(double[] doubleArray, List list)
在调用它时使用2种不同的类型。
答案 2 :(得分:0)
像这样(包括可以说是更优雅,更有效的getMedian版本):
public class Test
{
public double getMedian(double[] list)
{
double median = 0;
if (list != null && (list.length > 0))
{
// Sort ascending
Arrays.sort(list);
int numItems = list.length;
if ((numItems % 2) == 0)
{
// We have an even number of items - average the middle two
int middleIndex = numItems / 2;
double firstMiddleValue = list[middleIndex - 1];
double secondMiddleValue = list[middleIndex];
median = (firstMiddleValue + secondMiddleValue) / 2;
}
else
{
// Odd number of items - pick the middle one
median = list[(numItems / 2)];
}
}
return median;
}
public static void main(String[] args)
{
Test t = new Test();
double[] testValuesOfLengthOne = { 3.1415 };
double[] testValuesEvenLength = {22.5, 14.33, 100.849, 44.259, 0.0, 145000.0};
double[] testValuesOddLength = {22.5, 14.33, 100.849, 44.259, 0.0, 145000.0, -4.9};
System.out.println("Median of " + Arrays.toString(testValuesOfLengthOne) + " is " + t.getMedian(testValuesOfLengthOne));
System.out.println("Median of " + Arrays.toString(testValuesEvenLength) + " is " + t.getMedian(testValuesEvenLength));
System.out.println("Median of " + Arrays.toString(testValuesOddLength) + " is " + t.getMedian(testValuesOddLength));
}
}
这为您提供以下输出:
Median of [3.1415] is 3.1415
Median of [22.5, 14.33, 100.849, 44.259, 0.0, 145000.0] is 33.3795
Median of [22.5, 14.33, 100.849, 44.259, 0.0, 145000.0, -4.9] is 22.5