如何在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 = 42Average Of integer elements = 7
以上是 如何在C#中找到整数数组元素的平均值? 的全部内容, 来源链接: utcz.com/z/311462.html