首先,设置一个值数组-
int[] myArr = new int[] { 34, 23, 77, 67 };
要获得平均值,首先要获取数组元素的总和。
将总和除以数组的长度,将得到元素的平均值-
int sum = 0; int average = 0; for (int i = 0; i < len; i++) { sum += myArr[i]; } average = sum / len;
以下是在C#中获取数组的完整代码-
using System; public class Program { public static void Main() { int[] myArr = new int[] { 34, 23, 77, 67 }; 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("Average = " + average); } }
输出结果
Average = 50