C# calculate mean of the values in int array

本秂侑毒 提交于 2019-12-23 03:34:13

问题


What's the problem when I try to print the average of the values in int array and it prints out something totally different as many times as I have values.

int[] numbers;
numbers = new int[5];
Console.WriteLine("give five integer numbers:");
numbers[0] = Int32.Parse(Console.ReadLine());
numbers[1] = Int32.Parse(Console.ReadLine());
numbers[2] = Int32.Parse(Console.ReadLine());
numbers[3] = Int32.Parse(Console.ReadLine());
numbers[4] = Int32.Parse(Console.ReadLine());
int sum = 0;

foreach (int x in numbers) {
    sum += x;
    int aver = sum / numbers.Length;  
    Console.WriteLine("average: {0}",aver);
}

回答1:


Average should be outside the loop:

foreach (int x in numbers) 
{
   sum += x;
}

int aver = sum / numbers.Length;  
Console.WriteLine("average: {0}",aver);

Or using Linq Extension Methods:

Console.WriteLine("average: {0}", numbers.Average());



回答2:


You could rephrase the loops as

int sum = 0;
foreach (int x in numbers)
{
    sum += x;
}
int aver = sum / numbers.Length;

or simply do the calculation as

int aver = numbers.Average();

by using Linq.




回答3:


Or with linq : var aver = numbers.Average();

https://msdn.microsoft.com/en-us/library/bb399409(v=vs.110).aspx

I ll complete my answer with what is the hood under Average() so ;)

  public static double Average(this IEnumerable<int> source) {
       if (source == null) throw Error.ArgumentNull("source");
       long sum = 0;
       long count = 0;
       checked {
          foreach (int v in source) {
              sum += v;
              count++;
          }
       }
       if (count > 0) return (double)sum / count;
       throw Error.NoElements();
   }



回答4:


Change

foreach (int x in numbers) {
    sum += x;
    int aver = sum / numbers.Length;  Console.WriteLine("average: {0}",aver);
}

To

foreach (int x in numbers) {
    sum += x;
}
int aver = sum / numbers.Length;  Console.WriteLine("average: {0}",aver);


来源:https://stackoverflow.com/questions/37966950/c-sharp-calculate-mean-of-the-values-in-int-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!