这是给我的一个问题。我面临的挑战是知道如何从数组列表中找到平均值以及数组中最接近该平均值的值。所有这一切都是通过编写可以使用测试中给出的任何数组执行此操作的代码来实现的。
这是我编写类(class)的测试:
import static org.junit.Assert.*;
import org.junit.Test;
public class Question2Test
{
int[] arrayInts = {1, 1, 3, 4, 9};
private Question2 avg1;
private Question2 avg2;
private Question2 avg3;
@Test
public void testFindMiddle()
{
Question2 avg1 = new Question2();
assertEquals(1, avg1.getAverage());
Question2 avg2 = new Question2();
assertEquals(4, avg2.getAverage());
Question2 avg3 = new Question2();
assertEquals(0, avg3.getAverage());
}
//find what I need to do with "getAverage"
}
到目前为止我所拥有的:
/**
* Find the value in an array that is closest to the average.
*/
public class Question2
{
private int avg;
public double findMiddle(int[] arrays)
{
//Find the average
double sum = 0;
for(int i = 0; i < arrays.length; i++)
{
sum += arrays[i];
}
double avg = sum/arrays.length;
return avg;
// Now Find the value in an array that is closest to the average:
for(int i = 0; i < arrays.length; i++)
{
int arrays[i] = Math.abs(arrays[i] + 1);
if(arrays[i] == avg)
{
return arrays[i];
}
}
}
public int getAverage(int[] array) // is a getter: a method whose purpose is to return the value stored in an instance variable!
{
return avg;
}
}
所以第一个问题是它根本不需要我的秒数 for 循环。我能够找到平均值,但现在 Java 不接受我找到最接近它的值。
最佳答案
正如您所说,问题有两个不同的部分:
- 求平均值
- 在数组中查找最接近该平均值的数字。
关于问题1,在您的代码中,您的想法是正确的,但实现是错误的。您想要将数组中的所有元素相加,然后将该总和除以数组中的元素数量。实际上,您所需要做的就是将除法从循环中取出。它看起来像这样:
double sum = 0;
for(int i = 0; i < arrays.length; i++)
{
sum += arrays[i]; //the += takes the current value of sum and adds the array[i] value to it.
}
double avg = sum/arrays.length; //Since sum is a double avg can be a double as well.
对于第二部分,您想要在数组中找到最接近该平均值的数字。使用 Math.abs() 方法,您可以获得两个数字之间的差的绝对值。使用此方法,您可以循环遍历数组中的所有元素,对它们调用 Math.abs() 方法,并保存结果最小的元素。
关于java - 使用给定的 JUNIT 测试查找数组中最接近平均值的值 ~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51715866/