猿问

在数组 c# 中查找与数字最远和最接近的数字

我有一个练习,我需要找到最远和最接近某个数字(平均值)的数字。有人可以帮助我吗?这是我的代码:


Console.WriteLine("Geef 10 gehele positieve getallen.");

Console.WriteLine("Getal 1:");

int g1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 2:");

int g2 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 3:");

int g3 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 4:");

int g4 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 5:");

int g5 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 6:");

int g6 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 7:");

int g7 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 8:");

int g8 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 9:");

int g9 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Getal 10:");

int g10 = Convert.ToInt32(Console.ReadLine());

int gemiddelde = (g1 + g2 + g3 + g4 + g5 + g6 + g7 + g8 + g9 + g10)/10;

int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};


哔哔one
浏览 1373回答 2
2回答

jeck猫

如果你可以使用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 Listvar 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 closestvar closestTo = values.Aggregate((x, y) => Math.Abs(x - value) < Math.Abs(y - value) ? x : y);// same logic as closest except we keep the furthestvar furthestTo = values.Aggregate((x, y) => Math.Abs(x - value) > Math.Abs(y - value) ? x : y);&nbsp;
随时随地看视频慕课网APP
我要回答