VB.NET 数组求平均值
时间: 2024-08-31 12:00:25 浏览: 63
VB.net数组第一节
VB.NET中,数组求平均值是一个常见的编程任务。假设你有一个整数数组,你可以按照以下步骤计算其平均值:
1. 首先,你需要声明一个数组并初始化它,例如:
```vb.net
Dim numbers() As Integer = {10, 20, 30, 40, 50}
```
2. 确定数组的长度以便于遍历,可以使用`Length`属性:
```vb.net
Dim arrayLength As Integer = numbers.Length
```
3. 初始化一个变量来存储总和,通常初始化为0:
```vb.net
Dim sum As Integer = 0
```
4. 使用for循环遍历数组,将每个元素加到总和中:
```vb.net
For i As Integer = 0 To arrayLength - 1
sum += numbers(i)
Next
```
5. 计算平均值,即总和除以数组长度:
```vb.net
Dim average As Double = CDbl(sum) / arrayLength
```
6. 最后,`average`变量就包含了数组的平均值。
完整的代码示例如下:
```vb.net
Dim numbers() As Integer = {10, 20, 30, 40, 50}
Dim arrayLength As Integer = numbers.Length
Dim sum As Integer = 0
For i As Integer = 0 To arrayLength - 1
sum += numbers(i)
Next
Dim average As Double = CDbl(sum) / arrayLength
Console.WriteLine("数组的平均值是: " & average)
```
阅读全文