问题
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