所以,我试图创建一个生成20个低于100的随机整数的数组,我想只写出我从该数组中得到的高于平均值的数字,这里是代码I'使用,不能知道我现在要做什么......
PS:我知道我的foreach错了,我也能得到一些帮助吗?static void Main(string[] args)
{
int average, aboveAverage;
Random random = new Random();
for (int i = 0; i < 100; i++)
{
int[] vetor;
array = new int[20];
array[0] = random.Next(0, 100);
array[1] = random.Next(0, 100);
array[2] = random.Next(0, 100);
array[3] = random.Next(0, 100);
array[4] = random.Next(0, 100);
array[5] = random.Next(0, 100);
array[6] = random.Next(0, 100);
array[7] = random.Next(0, 100);
array[8] = random.Next(0, 100);
array[9] = random.Next(0, 100);
array[10] = random.Next(0, 100);
array[11] = random.Next(0, 100);
array[12] = random.Next(0, 100);
array[13] = random.Next(0, 100);
array[14] = random.Next(0, 100);
array[15] = random.Next(0, 100);
array[16] = random.Next(0, 100);
array[17] = random.Next(0, 100);
array[18] = random.Next(0, 100);
array[19] = random.Next(0, 100);
foreach (int elements in array)
{
average = elements / 20;
aboveAverage = ???
Console.WriteLine("{0} integers are above average.", aboveAverage);
}
Console.ReadKey();
}
}
}
}
所以,这就是我所做的,最后我检查它工作正常^ _ ^ thx为大家提供帮助,非常感谢,希望我能选择每个人的答案!
static void Main(string[] args)
{
int sumNumbers, average;
int aboveAverage = 0;
int[] array = new int[20];
Random random = new Random();
for (int i = 0; i < 20; i++)
{
array[i] = random.Next(0, 100);
}
sumNumbers = array.Sum();
average = sumNumbers / 20;
foreach (var elements in array)
{
if (elements > average)
{
aboveAverage++;
}
}
Console.WriteLine("{0} numbers are above average.", aboveAverage);
Console.ReadKey();
}
}
}
答案 0 :(得分:3)
将其拆分为两个步骤。首先计算平均值。使用linq它看起来像这样::
var average = array.Average();
然后只检索那些高于平均水平的人:
var aboveAverage = string.Join(", " array.Where(item => item > average));
Console.WriteLine($"{aboveAverage} integers are above average.");
$""
语法为C#6.0 String Interpolation 您还可以使用Enumerable.Repeat
和.Select
以更好的方式生成所有随机数:
var array = Enumerable.Repeat(0, 20).Select(item => random.Next(0, 100)).ToArray();
如果没有linq,则首先迭代集合一次以对所有项目求和,这样您就可以计算平均值,然后再次找到所有大于平均值的项目:
int sum = 0;
foreach(var item in array)
{
sum += item;
}
var average = sum * 1.0 / array.Length;
List<int> aboveAverageItems = new List<int>();
foreach(var item in array)
{
if(item > average)
{
//If you need to know how many items and not which then use a counter and increase
aboveAverageItems.Add(item);
}
}
Console.WriteLine($"{string.Join(", " aboveAverageItems)} integers are above average.");
答案 1 :(得分:1)
我同意上述评论,说这可能来自家庭作业。我想在你的代码中指出一些缺陷,并指出你正确的方向,希望你能自己解决这个问题:
希望这有帮助!
答案 2 :(得分:0)
没有linq,就这样做:
int sum = 0;
foreach (int elements in array)
{
sum = sum + elements;
}
var avg = sum / 20;
var aboveAvgCount = 0;
foreach (int elements in array)
{
if (elements > avg)
{
aboveAvgCount = aboveAvgCount + 1;
}
}