我有一个练习,我需要找到最远和最接近的数字到一定数量(平均值)。有人能帮助我吗?这是我的代码:
yourclass.sigleton.pazienti()
答案 0 :(得分:3)
如果您可以使用List<int>
代替数组,那么根据您的要求,您可以更轻松地进行编码,也可能更清晰。
让我们改变一下:
int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
进入这样的列表:
List<int> values = new List<int>(){g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
聚合将测试每个元素,直到列表完全经过测试。 因此,我们可以尝试获得最接近和最远的值,如此
// value you want to check is the average of the list.
// Average is already implemented for the List
var value = values.Average();
// will keep the closest value in the collection to our value we are looking for
// and keep testing with the following value to end up with the final closest
var closestTo = values.Aggregate((x, y) => Math.Abs(x - value) < Math.Abs(y - value) ? x : y);
// same logic as closest except we keep the furthest
var furthestTo = values.Aggregate((x, y) => Math.Abs(x - value) > Math.Abs(y - value) ? x : y);
答案 1 :(得分:0)
我希望这个例子可以帮助你,即使它是在java中。
//Your array with the numbers
int[] data = {12, 123, 65, 23, 4, 213, 32, 342, 21, 15};
int testNum = 27; //Your test value
int holderHigh = testNum;
for(int i = 0; i < data.length; i++){//Goes through the array
//If the holder is lower than a value in the array it will get stored
if(holderHigh < data[i]){
holderHigh = data[i];
}
}
int holderLow = testNum;
for(int k = 0; k < data.length; k++){//Goes through the array
//If the holder is higher than a value in the array it will get stored
if(holderLow > data[k]){
holderLow = data[k];
}
}
System.out.println(holderHigh + " and " + holderLow +
" is the number farthest away from " + testNum);stNum);