如何在 C# 中查找整数数组元素的平均值?
以下是我们整数数组 −
int[] myArr = new int[6] { 8, 4, 2, 5, 9, 14 };
首先,获取数组的长度,然后遍历数组来查找元素的和。之后,用该长度除以该和。
int len = myArr.Length; int sum = 0; int average = 0; for (int i = 0; i < len; i++) { sum += myArr[i]; } average = sum / len;
以下是完整代码
示例
using System; public class Program { public static void Main() { int[] myArr = new int[6] { 8, 4, 2, 5, 9, 14 }; int len = myArr.Length; int sum = 0; int average = 0; for (int i = 0; i < len; i++) { sum += myArr[i]; } average = sum / len; Console.WriteLine("Sum = " + sum); Console.WriteLine("Average Of integer elements = " + average); } }
输出
Sum = 42 Average Of integer elements = 7
广告