用户输入 x 个整数,这些整数存储在数组('dataA')中。计算数据的平均值,并应删除最远的元素(“异常值”)。我不知道如何删除该元素并且需要知道。
此外,程序会删除一个异常值,计算新的平均值并删除下一个异常值,直到剩下一个元素。
public static Scanner sc1 = new Scanner(System.in);
public static int dataN = sc1.nextInt();//number of data elements
public static double[] dataA = new double[dataN];//array storing elements
for(int index = 0; index<dataA.length; index++)//increments index
{
double lengthA = dataA.length;//length of array
double avg = sum/lengthA;//avg of elements
double outlier = dataA[0];//outlier
double index_outlier = 0;//index of outlier
double dif_in = Math.abs(avg - dataA[index]);//difference of avg & element
double dif_out = Math.abs(avg - outlier);//difference of avg & outlier
if(dif_in > dif_out)
{
outlier = dataA[index];
index_outlier = index;
}
最佳答案
您可以尝试将异常值与数组的最后一个元素交换并继续使用数组,但考虑少一个元素。如果您对此感到满意,那么您可以使用Array
,例如:
public static void main(String[] args) throws FileNotFoundException {
double[] dataArray = new double[] {1.5,2.5,3.5,4.5,7.5,8.5,2.5};
int arraySizeToConsider = dataArray.length;
double outlier;
int index_outlier;
double avg;
double diffInOutlierAndAvg;
while(arraySizeToConsider > 0) {
outlier = dataArray[0];
index_outlier = 0;
avg = computeSum(dataArray,arraySizeToConsider) / (arraySizeToConsider);//avg of elements
diffInOutlierAndAvg = Math.abs(avg - outlier);
// find outlier
for(int index = 0; index<arraySizeToConsider; index++)//increments index
{
if(Math.abs(avg - dataArray[index]) > diffInOutlierAndAvg) {
outlier = dataArray[index];
index_outlier = index;
}
}
double temp = dataArray[arraySizeToConsider -1];
dataArray[arraySizeToConsider -1] = outlier;
dataArray[index_outlier] = temp;
arraySizeToConsider = arraySizeToConsider -1;
System.out.println("Average: " + avg + " Outlier: " + outlier + " index " + index_outlier + " array size to consider: " +arraySizeToConsider);
}
}
private static double computeSum(double[] array, int arraySizeToConsider) {
double sum = 0;
for (int i = 0; i < arraySizeToConsider; i++) {
sum = sum + array[i];
}
return sum;
}
这是输出:
平均值:4.357142857142857 异常值:8.5 索引 5 要考虑的数组大小:6
平均值:3.6666666666666665 异常值:7.5 索引 4 要考虑的数组大小:5
平均值:2.9 离群值:4.5 需要考虑的索引 3 数组大小:4
平均值:2.5 离群值:1.5 索引 0 要考虑的数组大小:3
平均值:2.8333333333333335 异常值:3.5 索引 2 要考虑的数组大小:2
平均值:2.5 异常值:2.5 索引 0 要考虑的数组大小:1
平均值:2.5 异常值:2.5 索引 0 要考虑的数组大小:0
还有一些优化留给您去解决。
提示:每次发现异常值时,我们是否都需要计算总和;)?
关于java - 从数组中删除元素(特定于代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178835/