如何在 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
广告