gpt4 book ai didi

java - 确定数组中特定元素的总和

转载 作者:行者123 更新时间:2023-11-30 08:52:26 24 4
gpt4 key购买 nike

我有一个数组,它存储了用户输入的一系列 double 值。数组的长度是用户的选择,因此会有所不同。我将数字放入一个循环中,该循环计算平均值并将离群值交换到数组的最后一个索引。在没有离群值的情况下计算新的平均值,并将新的离群值交换到数组的倒数第二个索引。重复这个循环,直到剩下 1 个元素。

但是异常值并没有从数组中移除,所以我需要在没有异常值的情况下以某种方式计算平均值。我在想我可以指定要包含在平均值中的元素的索引。

最佳答案

看起来流程应该是这样的:

  1. 通过遍历数组直到 n 个元素来计算平均值。
  2. 查找异常值。
  3. 与最后一个元素交换。
  4. 现在将 n 设置为(数组的当前大小 - 1)。并继续这样做直到 size = 0;

我已经编译了一个可能适合你的代码。请记住,您可能需要根据您的要求进行某些小的更改。

  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/30180141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com